I know about passing data between components in html using the @Input but how to pass them via ts files? This is the parent file. I wish to pass this.category and this.data to the SelectCustomersProjectModalComponent.
public openSelectRolesModal() {
this.modal.open(
SelectCustomersProjectModalComponent,
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}
CodePudding user response:
Catch the child in a ViewChild and configure it in a AfterViewInit
Parent... implements AfterViewInit {
@ViewChild(SelectCustomersProjectModalComponent) selectCustomers: SelectCustomersProjectModalComponent;
ngAfterViewInit(){
this.selectCustomers.category = category
this.selectCustomers.data = data
}
}
CodePudding user response:
To be able to pass data into a Modal Material dialog try the following:
In your component that opens the dialog add the JSON data as shown within the parameter of the modal dialog Open() method:
public openSelectRolesModal() {
this.modal.open(
SelectCustomersProjectModalComponent,
data: {
key1: 'some value 1'
}
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}
In your dialog component source, import the Material dialog library and injection library as shown:
import {Component, Inject} from '@angular/core';
import {MatDialog, MAT_DIALOG_DATA} from '@angular/material/dialog';
Then declare an interface for the data structure:
export interface MyDialogData {
key1: string;
}
In your component implementation, inject the dialog data as shown within the constructor:
@Component({
selector: 'my-dialog',
templateUrl: 'my-dialog.html',
})
export class SelectCustomersProjectModalComponent {
constructor(@Inject(MAT_DIALOG_DATA) public data: MyDialogData) {}
}
Once you have implemented the above, the modal component will be able to use your parameter value of type MyDialogData within your modal component.
For your this.category and this.data you can include them in the class structure as follows:
export class MyDialogData {
key1: MyCategory;
key2: MyData;
}
Where MyCategory and MyData are classes for the this.category and this.data properties within your calling component.
Then pass the above data object into your modal dialog parameter as shown:
public openSelectRolesModal() {
this.modal.open(
SelectCustomersProjectModalComponent,
data: {
key1: this.category,
key2: this.data
}
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}