如何将数据从一个组件传递到另一个在ts文件?



我知道在html中使用@Input传递组件之间的数据,但如何通过ts文件传递它们?这是父文件。我希望通过这个法案。分类和这个。

public openSelectRolesModal() {   
this.modal.open(
SelectCustomersProjectModalComponent,
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}

要能够将数据传递到模态材质对话框中,请尝试以下操作:

在打开对话框的组件中添加JSON数据,如模式对话框Open()方法的参数所示:

public openSelectRolesModal() {   
this.modal.open(
SelectCustomersProjectModalComponent,
data: {
key1: 'some value 1'
}
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}

在对话框组件源代码中,导入Material对话框库和注入库,如下所示:

import {Component, Inject} from '@angular/core';
import {MatDialog, MAT_DIALOG_DATA} from '@angular/material/dialog';

为数据结构声明一个接口:

export interface MyDialogData {
key1: string;
}

在组件实现中,注入对话框数据,如下所示:

@Component({
selector: 'my-dialog',
templateUrl: 'my-dialog.html',
})
export class SelectCustomersProjectModalComponent {
constructor(@Inject(MAT_DIALOG_DATA) public data: MyDialogData) {}
}

一旦你实现了上面的内容,模态组件将能够在你的模态组件中使用MyDialogData类型的参数值。

For your this。分类和这个。您可以将它们包含在类结构中,如下所示:

export class MyDialogData {
key1: MyCategory;
key2: MyData;
}

其中MyCategory和MyData是this的类。分类和这个。调用组件中的数据属性。

然后将上述数据对象传递给模态对话框参数,如下所示:

public openSelectRolesModal() {   
this.modal.open(
SelectCustomersProjectModalComponent,
data: {
key1: this.category,
key2: this.data
}
).afterClosed().subscribe((users: User[]) => {
if ( ! users) return;
this.setRoles(users);
});
}

在ViewChild中捕获子元素并在AfterViewInit中配置

Parent... implements AfterViewInit {
@ViewChild(SelectCustomersProjectModalComponent) selectCustomers: SelectCustomersProjectModalComponent;
ngAfterViewInit(){
this.selectCustomers.category = category
this.selectCustomers.data = data
}
}