- 脚手架生成
ng new modal-app
npm i
cd modal-app/
ng g c modal
文件结构为:
- 导入佐罗(ant design)样式
npm install ng-zorro-antd --save
在angular.json中引入:
"styles": [
"node_modules/ng-zorro-antd/ng-zorro-antd.min.css"
]
在style.css中引入:
@import "~ng-zorro-antd/ng-zorro-antd.min.css";
- app.module.ts
注意要导入BrowserAnimationsMoule,删除原来的BrowserModule,不然后面的zorro弹出框会报错。
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { ModalComponent } from './modal/modal.component';
import {FormsModule} from "@angular/forms";
import {NzModalModule} from "ng-zorro-antd/modal";
import {NzButtonModule} from "ng-zorro-antd/button";
@NgModule({
declarations: [
AppComponent,
ModalComponent
],
imports: [
BrowserAnimationsModule,
FormsModule,
NzModalModule,
NzButtonModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- app.component.ts
此处注意导入ModalComponent,并且注意@ViewChild语法。其中的detail函数调用了子组件Modal的show()方法。其中使用了@ts-ignore注解抑制报错,原因未知。
import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalComponent} from "./modal/modal.component";
const strings: string[] = [
"zhang",
"wang",
"ruan"
]
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
@ViewChild('modal', {static: false})
public modal: ModalComponent | undefined
strings = strings;
constructor() {
}
ngOnInit(): void {
}
getModal() {
this.modal?.showModal()
}
detail(name: string) {
this.modal.show(name);
}
}
- app.component.html
此处遍历字符串数组,并绑定(click)事件,且当前值作为detail函数参数。注意Angular为单页应用,在主页面中应该包含子组件的选择器,以及#属性。
<li *ngFor="let str of strings">
<button nz-button (click)="detail(str)">{{str}}</button>
</li>
<nz-demo-modal-basic #modal></nz-demo-modal-basic>
- modal.component.ts
弹出框的显示逻辑由isVisible控制,在modal.component.html中进行了属性[(nzVisible)]的双向绑定。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-modal-basic',
templateUrl: 'modal.component.html',
})
export class ModalComponent {
isVisible = false;
na: any;
nameme: any;
constructor() {}
hello(): void {
console.log('hello')
}
handleOk(): void {
console.log('Button ok clicked!');
this.isVisible = false;
}
handleCancel(): void {
console.log('Button cancel clicked!');
this.isVisible = false;
}
showModal(): void{
this.isVisible = true;
}
show(na:string): void{
this.nameme = na;
this.isVisible = true;
console.log(na)
}
}
- modal.component.html
可以看到[(nzVisible)]的双向绑定,决定是否弹出。
<nz-modal [(nzVisible)]="isVisible" (nzOnCancel)="handleCancel()" (nzOnOk)="handleOk()">
<ng-container *nzModalContent>
<p>{{nameme}}</p>
<p>{{nameme}}</p>
<p>{{nameme}}</p>
</ng-container>
</nz-modal>
- 最终效果
9. 注意事项!!! @ViewChild语法 父模板中插入子模版并使用#
|