【问题标题】:Passing param using directive to child component angular使用指令将参数传递给子组件角度
【发布时间】:2020-02-06 14:04:15
【问题描述】:

我尝试创建可以使用指令传递参数的子组件,但我仍然没有找到任何创建 itu 的教程。

我已经尝试了一些: Get reference to a directive used in a component

这是我的代码

这是来自父组件的模板

<child-component>
    <grand-child-directive [name]='Ghandy'></grand-child-directive >
    <grand-child-directive [name]='Ani'></grand-child-directive >
    <grand-child-directive [name]='Budi'></grand-child-directive >
</child-component>

这个孙子指令指令

@Directive({
  selector: 'grand-child-directive ',
})
export class gc{
  @Input() name:string;
}

这是我的子组件

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.scss'],

})

export class childComponent implements OnInit 

@ViewChildren(gc) gc: gc;

  constructor(
  ) {

  }
  ngOnInit() {
    console.log(gc.name)
  }
}

当我 console.log gc.name 时,我得到了未定义,而不是数组 [Ghandy, Ani, Budi]

我很乐意提供任何帮助。

【问题讨论】:

  • 为什么要将指令投射到组件中?
  • @Chellappan,我需要处理子组件中的名称([Ghandy,Ani,Budi]),除了名称之外,我还需要地址之类的其他内容
  • 为什么不在子组件中使用@Input()pass-data-to-child-component.

标签: angular typescript


【解决方案1】:

您应该使用 ContentChildren 而不是 ViewChildren。然后你应该实现 AfterContentInit 生命周期钩子来访问该值。

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.scss'],

})

export class childComponent implements OnInit,AfterContentInit 

 @ContentChildren(GrandChildDirective) gc:QueryList<GrandChildDirective> ;

  constructor(
  ) {

  }
  ngAfterContentInit() {
     console.log(this.gc.toArray().map(item=>item.name));
  }
}

Example

【讨论】:

    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2018-03-13
    • 2015-06-28
    相关资源
    最近更新 更多