angular - 在 Angular 9 中将数据传递给指令

标签 angular directive

我创建一个包含组件的指令:HomechildrenComponent

<p>{{name}}</p>
<address>
  <strong>Twitter, Inc.</strong><br>
  1355 Market St, Suite 900<br>
  San Francisco, CA 94103<br>
  <abbr title="Phone">P:</abbr> (123) 456-7890
</address>

和指令

@Directive({
  selector: '[appRenderhomechildcp]'
})

export class RenderhomechildcpDirective {
  private name : string;
  @Input('appRenderhomechildcp') set appRenderhomechildcp(name : string){
    this.name = name;
  };

  childComponent : ComponentRef<HomechildrenComponent>;

  constructor(private container : ViewContainerRef, private cpFactoryResolve : ComponentFactoryResolver) 
  { 
    const componentFactory = this.cpFactoryResolve.resolveComponentFactory(HomechildrenComponent);
    this.childComponent = this.container.createComponent(componentFactory);
    this.childComponent.instance.name = this.name;
    
  }

在我将指令调用到 Home.Component.ts 后

lsFood = ['Candy', 'Milk', 'Juice fruite', 'Cream']

<div *ngFor="let item of lsFood">
    <div [appRenderhomechildcp]="item"></div>
</div>

但它无法将 HomeComponent 中的数据绑定(bind)到指令。我该如何处理? 谢谢

最佳答案

您的 @Input 属性尚未在构造函数中初始化。将 name 初始化移动到 ngOnInit钩子(Hook)并且它应该可以工作:

export class RenderhomechildcpDirective implement OnInit {
  ...
  ngOnInit() {
    this.childComponent.instance.name = this.name;
  }

<强> Ng-run Example

关于angular - 在 Angular 9 中将数据传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62496875/

相关文章:

javascript - Angularjs 字符串值或表达式?

c++ - #ifndef#define 指令是什么意思

AngularJS - 在多个 map 的指令中异步加载谷歌地图脚本

javascript - Angular 指令不适用于 *ngIf。从组件调用指令

templates - AngularJS + Karma + Ng-html2js => 无法实例化模块 ...html

java - 在不同端口的同一个 tomcat 上部署 Angular 5 和 spring boot 应用程序

javascript - 如何在 Angular 库的 node_modules 文件夹之外使用 *.d.ts?

angular - 在 angular2 中如何获取新 @Angular/router 的 RouteParams - 似乎不存在

css - 如何管理多个样式表并使应用程序高效

javascript - 如何解决 "Cannot read property ' scrollIntoView' of undefined"?