Angular 使用父级指令获取嵌套元素
Angular get nested element using directive on parent
这是我的代码
<parent my-directive [toHide]="childRef">
<child bottom right #childRef>
<button>Some text </button>
</child >
</parent >
我在父元素上有 my-directive
,我想访问子元素并对其应用一些样式。
所以在我的指令中,我有以下内容。
export class MyDirective {
@Input("toHide") localRef;
constructor(public element:ElementRef,public renderer:Renderer) {
console.log('Hello MyDirective Directive');
}
ngAfterViewInit() {
console.log("All Transtition set");
console.log(this.localRef);
this.renderer.setElementStyle(this.localRef, 'webkitTransition', 'transform 500ms,top 500ms');
}
如您所见,我正在使用 this.renderer
来设置元素的样式,但我得到以下结果。
ERROR Error: Uncaught (in promise): TypeError: el.style is undefined
欢迎提供这方面的任何帮助。
如果 <child>
是一个普通的 HTML 元素(没有组件)那么这应该可以工作(添加 nativeElement
)
this.renderer.setElementStyle(
this.localRef.nativeElement, 'webkitTransition', 'transform 500ms,top 500ms');
如果 <child>
是一个 Angular 组件更改此行
@Input("toHide") localRef;
到
@ContentChild('childRef', { read: ElementRef }) localRef;
并删除 [toHide]="childRef"
如果元素带有模板变量
是一个普通的 HTML 元素,读取引用 returns 和 ElementRef
并且可以使用 nativeElement
属性.
访问实际元素
如果它是组件或承载指令,则读取引用 returns 不能用于访问 DOM 元素的组件或指令实例。
@ViewChild(ren)
和 @ContentChild(ren)
允许使用 read
参数从模板变量引用中指定要 return 的内容,但是从模板中访问模板变量引用没有提供。
不过我建议使用
@HostBinding('class.is-transition')
isTransition:boolean false;
在指令中使用CSS like
parent[host-directive] > child {
-webkit-transition: transform 500ms,top 500ms;
}
应用样式。
这是我的代码
<parent my-directive [toHide]="childRef">
<child bottom right #childRef>
<button>Some text </button>
</child >
</parent >
我在父元素上有 my-directive
,我想访问子元素并对其应用一些样式。
所以在我的指令中,我有以下内容。
export class MyDirective {
@Input("toHide") localRef;
constructor(public element:ElementRef,public renderer:Renderer) {
console.log('Hello MyDirective Directive');
}
ngAfterViewInit() {
console.log("All Transtition set");
console.log(this.localRef);
this.renderer.setElementStyle(this.localRef, 'webkitTransition', 'transform 500ms,top 500ms');
}
如您所见,我正在使用 this.renderer
来设置元素的样式,但我得到以下结果。
ERROR Error: Uncaught (in promise): TypeError: el.style is undefined
欢迎提供这方面的任何帮助。
如果 <child>
是一个普通的 HTML 元素(没有组件)那么这应该可以工作(添加 nativeElement
)
this.renderer.setElementStyle(
this.localRef.nativeElement, 'webkitTransition', 'transform 500ms,top 500ms');
如果 <child>
是一个 Angular 组件更改此行
@Input("toHide") localRef;
到
@ContentChild('childRef', { read: ElementRef }) localRef;
并删除 [toHide]="childRef"
如果元素带有模板变量
是一个普通的 HTML 元素,读取引用 returns 和 ElementRef
并且可以使用 nativeElement
属性.
如果它是组件或承载指令,则读取引用 returns 不能用于访问 DOM 元素的组件或指令实例。
@ViewChild(ren)
和 @ContentChild(ren)
允许使用 read
参数从模板变量引用中指定要 return 的内容,但是从模板中访问模板变量引用没有提供。
不过我建议使用
@HostBinding('class.is-transition')
isTransition:boolean false;
在指令中使用CSS like
parent[host-directive] > child {
-webkit-transition: transform 500ms,top 500ms;
}
应用样式。