简体   繁体   中英

Passing param using directive to child component angular

i trying to create child component that can passing param using directive, but i still not found any tutorial to create itu.

i have try some from this: Get reference to a directive used in a component

here my code

This is the template from parent 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>

this grand-child-directive directive

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

This is my child-component

@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)
  }
}

when i console.log gc.name, i got undefined, not array [Ghandy, Ani, Budi]

I would be glad for any help.

You should use ContentChildren instead of ViewChildren. Then you should implement AfterContentInit lifecycle hook to access the value.

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM