1

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.

Hansen
  • 650
  • 1
  • 11
  • 32
  • Why are you projecting directive into component? – Chellappan வ Oct 09 '19 at 09:17
  • @Chellappan, i need to process the name ([Ghandy, Ani, Budi]) in child component, and besides the name, I also need something else like address – Hansen Oct 09 '19 at 09:21
  • Why not using `@Input()` in the child-component? [pass-data-to-child-component](https://www.tektutorialshub.com/angular/angular-passing-data-child-component/). – brandt.codes Oct 09 '19 at 09:37

1 Answers1

2

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60