【发布时间】:2018-03-15 14:07:15
【问题描述】:
我有一个对话框子组件 DeleteAssociationDialog,其中包含一个 openDeleteAssociationDialog 方法:
删除关联-dialog.component.ts
import { Component } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material';
@Component({
selector: 'app-delete-association-dialog',
templateUrl: 'delete-association-dialog.component.html',
styleUrls: ['delete-association-dialog.component.css']
})
export class DeleteAssociationDialogComponent {
constructor(
public dialog: MatDialog,
public dialogRef: MatDialogRef<DeleteAssociationDialogComponent>) { }
openDeleteAssociationDialog(): void {
let dialogRef = this.dialog.open(DeleteAssociationDialogComponent, {
width: '250px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
}
当点击父组件(app.component)HTML中的按钮时应该显示对话框,我正在使用@ViewChild建立引用:
app.component.html [片段]
<button mat-icon-button color="warn" (click)="child.openDeleteAssociationDialog()">
<mat-icon>delete</mat-icon>
</button>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material';
import { AppComponent } from './app.component';
import { DeleteAssociationDialogComponent } from './delete-association-dialog/delete-association-dialog.component';
import { MatDialogRef} from '@angular/material/dialog'
@NgModule({
declarations: [
AppComponent,
DeleteAssociationDialogComponent,
],
entryComponents: [DeleteAssociationDialogComponent],
imports: [
BrowserModule,
NgModule,
BrowserAnimationsModule,
MatButtonModule,
MatInputModule,
FormsModule
MatDialogModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material';
import { DeleteAssociationDialogComponent } from './delete-association-dialog/delete-association-dialog.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css', './app.component.panel.css']
})
export class AppComponent {
@ViewChild('DeleteAssociationDialogComponent') child: DeleteAssociationDialogComponent;
}
出现错误—— "ERROR TypeError: Cannot read property 'openDeleteAssociationDialog' of undefined"
我错过了什么?如何正确引用父组件 HTML 模板中的子组件方法?
【问题讨论】:
-
你为什么要这样做?这听起来像是不好的做法
-
请添加您的
/app.component.html代码 -
这个想法是划分对话框组件,因为我真的不想在 app.component.ts 中有多个 @Component。我是 Angular 的新手,所以还不熟悉它的最佳实践,但是我在单个 app.component.ts 中的每个对话框都有多个 @ Component 似乎肯定是一种不好的做法:)
-
@OvidiuDolha 在调用方法的地方添加了它的片段
-
@porgo 我试过了,得到了'NullInjectorError: No provider for MatDialogRef!',我还读到对话框不需要它
标签: angular typescript angular5