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.

3
  • Why are you projecting directive into component? Commented Oct 9, 2019 at 9: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 Commented Oct 9, 2019 at 9:21
  • Why not using @Input() in the child-component? pass-data-to-child-component. Commented Oct 9, 2019 at 9:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.