如何使用ViewChild / ContentChild从指令中查找指令?

时间:2016-07-15 09:39:03

标签: angular

我有一个组件comp,其中含有指令findTarget

<comp findTarget>
</comp>

comp包含target指令的元素:

@Component({
  selector: 'comp',
  template: `
    <div target>
      Target
    </div>
  `,
  directives: [Target]
})

我想从target指令中找到findTarget指令:

@Directive({
  selector: '[findTarget]'
})
export class FindTarget {
  @ContentChild(Target) ctarget: Target;
  @ViewChild(Target) vtarget: Target;

  ngAfterContentInit() {
    console.log('Content', this.ctarget)
  }

  ngAfterViewInit() {
    console.log('View', this.vtarget)
  }
}

但我得到

Content undefined
View undefined

完整代码: http://plnkr.co/edit/kc6q445iT1TcLqexqqAg?p=preview

更新 如果我将target元素从comp元素移动到其模板中,则ContentChild似乎有效: http://plnkr.co/edit/3MQj2Dv8tK036EL8GU8f?p=preview 但那不是我想要的。

1 个答案:

答案 0 :(得分:1)

指令没有模板,因此您无法直接获得ViewChild

您可以尝试使用这样的父引用:

@Directive({
  selector: '[target]'
})
export class Target {}

@Directive({
  selector: '[findTarget]'
})
export class FindTarget {
  constructor(@Inject(forwardRef(() => App)) private app: App) {}

  ngAfterViewInit() {
    console.log('View', this.app.vComp.vtarget) 
  }
} 

@Component({ 
  selector: 'comp',
  template: `
    <div target>
      Target
    </div>
  `,
  directives: [Target]
}) 
export class Comp {
  @ViewChild(Target) vtarget: Target;
}

@Component({
  selector: 'my-app',
  template: `
    <comp findTarget>
    </comp>
  `,
  directives: [Comp, FindTarget]
})
export class App {
   @ViewChild(Comp) vComp: Comp;
}

plunker