CAlex
CAlex

Reputation: 1140

Angular Material create a specific $event in a component file

I have a Chip Component that has an input which fires events for adding chips to a list. I gain access to this element via @ViewChild("chipInput", { static: true }) chipInput;

I am attempting to call my add(event: MatChipInputEvent) method from another component. Obviously, I need to pass in a valid MatChipInputEvent.

I have tried this:

let chips = this.comp.componentInstance.componentRef.instance as ChipInputComponent;

const myEvent: MatChipInputEvent = {
    input: chips.chipInput.nativeElement as HTMLInputElement,
    value: item
};

chips.add(event);

This does not appear to work. The input property of myEvent does not appear to be a valid HTMLInputElement. Is there a way to get this HTMLInputElement via viewchild from the DOM?

Upvotes: 0

Views: 631

Answers (1)

Walter Luszczyk
Walter Luszczyk

Reputation: 1522

It is important where the code you mentioned exists.

If it is inside ngOnInit, the static should be true.

It it happens after OnInit hook (i.e. in your method), then you should declare @ViewChild("chipInput", { static: false }) chipInput;

Read more on this https://angular.io/guide/static-query-migration

Further, if you want handle chipInput element, you can just write this.chipInput.*

Upvotes: 2

Related Questions