Angular做项目的时候,难免会用到弹框(即模态框),如果模态框里面有一张表格,表格里面的数据需要从父组件(这里暂且先说成父组件吧!)里面获取,模态框的表格里面的数据经过修改,又传回给父组件,这种通讯方式该怎么实现?我们先来看一下最基本的自定义弹框代码,看看有没有什么突破口。
一、基本的自定义弹框代码
1.demo目录
----------app.component.ts
----------app.component.html
----------app.module.ts
----------confirm(文件夹)
------------confirm.component.ts
------------confirm.component.html
2.项目代码
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from'@angular/core';
import { CommonModule } from"@angular/common";
import { BootstrapModalModule } from'ngx-bootstrap-modal';
import { AppComponent } from'./app.component';
import { ConfirmComponent } from'./confirm/confirm.component';
@NgModule({
declarations: [
AppComponent,
ConfirmComponent
],
imports: [
CommonModule,
BrowserModule,
BootstrapModalModule
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [
ConfirmComponent
]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { ConfirmComponent } from'./confirm/confirm.component';
import { DialogService } from"ngx-bootstrap-modal";
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title= 'app';
constructor(private dialogService:DialogService) {}
showConfirm() {this.dialogService.addDialog(ConfirmComponent, {
title:'Confirm title',
message:'Confirm message'})
.subscribe((isConfirmed)=>{if(isConfirmed) {}else{}
});
}
}
app.component.html
弹框
confirm.component.ts
import { Component } from '@angular/core';
import { DialogComponent, DialogService } from"ngx-bootstrap-modal";
export interface ConfirmModel {
title:string;
message:string;
}
@Component({
selector:'confirm',
templateUrl:'./confirm.component.html',
styleUrls: ['./confirm.component.css']
})
export class ConfirmComponent extends DialogComponentimplements ConfirmModel {
title: string;
message: string;//构造函数需要一个DialogService参数
constructor(dialogService: DialogService) {
super(dialogService);
}
confirm() {//result是一个boolean类型,这一点取决于{DialogComponent}
this.result = true;//close() 方法是由 `DialogComponent` 定义的,用于关闭模态框。在HTML模板中也有可以调用。
this.close();
}
}
confirm.component.html
×
{{title}}