代码之家  ›  专栏  ›  技术社区  ›  krv

使用父对象上的指令获取嵌套元素

  •  1
  • krv  · 技术社区  · 8 年前

    <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

    我们感谢您在这方面提供的任何帮助。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Günter Zöchbauer    8 年前

    如果 <child> nativeElement )

    this.renderer.setElementStyle(
        this.localRef.nativeElement, 'webkitTransition', 'transform 500ms,top 500ms');
    

    如果 <儿童>

    @Input("toHide") localRef;
    

    @ContentChild('childRef', { read: ElementRef }) localRef;
    

    如果元素具有模板变量 是纯HTML元素,读取引用返回 ElementRef 可以使用 nativeElement公司 所有物

    @ViewChild(ren) @ContentChild(ren) 允许使用 read 参数,但从模板内访问模板变量引用并不能提供该参数。

    但是我建议使用

    @HostBinding('class.is-transition')
    isTransition:boolean false;
    

    在指令中使用类似CSS的

    parent[host-directive] > child {
      -webkit-transition: transform 500ms,top 500ms;
    }