新建一个模态框的共通组件
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-custom-modal',
template: `
<nz-modal
[nzTitle]="title"
[nzVisible]="isVisible"
(nzOnCancel)="handleCancel()"
(nzOnOk)="handleOk()"
>
<ng-container *ngTemplateOutlet="content"></ng-container>
</nz-modal>
`,
})
export class CustomModalComponent implements OnInit {
@Input() title: string;
@Input() isVisible:boolean;
@Input() content: any;
@Output() onCancel = new EventEmitter<void>();
@Output() onOk = new EventEmitter<void>();
constructor() {}
ngOnInit(): void {
console.log("child :", this.isVisible);
}
handleCancel() {
console.log("child: cancel");
this.isVisible = false;
this.onCancel.emit();
}
handleOk(){
console.log("child: ok");
this.isVisible = false;
this.onOk.emit();
}
}
然后父组件对共通组件进行调用
父组件的html
<button (click)="openDialog()">Open Dialog</button>
<app-custom-modal [isVisible]="isDialogOpen" [content]="myFormContent" (onCancel)="closeDialog()" (onOk)="closeDialog()"></app-custom-modal>
<ng-template #myFormContent>
<div class="myForm">
<form [formGroup]="form">
<!-- 这里是你的表单内容 -->
<nz-form-item>
<nz-form-label>Your Name</nz-form-label>
<nz-form-control>
<input nz-input formControlName="name" />
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-label>Your email</nz-form-label>
<nz-form-control>
<input nz-input formControlName="email" />
</nz-form-control>
</nz-form-item>
</form>
</div>
</ng-template>
父组件的ts
isDialogOpen = false;
openDialog() {
this.isDialogOpen = true;
}
closeDialog() {
console.log("close dialogz");
this.isDialogOpen = false;
console.log(this.form.value);
}
几个注意的地方。
1,子组件的ok,cancel的事件一定要给父组件传递, 父组件的ok,cancel的方法一定要控制他自己变量的ture,false的设置, 不然会导致子组件只会弹出一次,第二次点击没有任何反应。
2. [content]="myFormContent",myFormContent是一个ng-template的模板ID,写法注意一下
3.关于ng-content的用法详细再记录一下
当我们在自定义组件的模板中使用<ng-content>
指令时,它允许我们在父组件中引用该组件并插入任意内容。这使得我们可以在父组件中根据需要动态添加和传递内容给自定义组件。
在上面的示例代码中,父组件使用了自定义的弹出框组件app-custom-modal
,并在其中使用了<ng-content></ng-content>
。这样,当父组件使用app-custom-modal
组件时,在<ng-content></ng-content>
的位置,父组件中传入的内容将会被动态插入到自定义组件的模板中。
具体来说,当父组件中使用<app-custom-modal>
标签时,它将被视为一个自定义组件的实例。在自定义组件的模板中,<ng-content></ng-content>
表示一个占位符,用于接收父组件中传入的内容。这样,父组件中的任何内容都可以通过<app-custom-modal>
标签内部的形式传递给自定义组件。
例如,在父组件中有以下代码:
<app-custom-modal> <p>这是父组件中传入的内容</p> </app-custom-modal>
那么,在自定义组件的模板中,<ng-content></ng-content>
将会被替换为<p>这是父组件中传入的内容</p>
,从而实现了动态插入父组件传入的内容。
通过使用<ng-content>
指令,我们可以在自定义组件中以灵活的方式接收和处理父组件传递的内容,从而实现更好的复用性和可定制性