angular公共组件的写法
angular的最大的优点便是它的组件化和模块化,本文要讲的是它的组件化:
说到组件就必须说到组件通信,公共组件的通信方式就是父子组件通信.
父子组件通信的三要素: input ,output和emit()
@Input() 定义输入的变量
@Output() 定义输出变量
首先是子组件
popup.html
<div class="popup-wrapper"><div class="title"><p>Bank Name: {{bankName}}p><p>Account Id: {{id}}p><button (click)="show()">显示button><button (click)="hide()">隐藏button>div><div class="content" *ngIf="flag"><button (click)="toggle()">Togglebutton><div [hidden]="!visible"><p>提示信息p>div>div>
div>
popup.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';@Component({selector: 'app-popup',templateUrl: './popup.component.html',styleUrls: ['./popup.component.scss']
})
export class PopupComponent implements OnInit {@Input() bankName: string;@Input('account-id') id: string; // 可选的仅供模板中使用的名字,默认就是绑定属性的名字@Output() showPopoup: EventEmitter<any> = new EventEmitter()@Output() hidePopoup: EventEmitter<any> = new EventEmitter()constructor() { }public flag:boolean = false;visible: boolean = true;show() {this.flag = true;this.showPopoup.emit(true);}hide() {this.flag = false;this.hidePopoup.emit(false);}toggle() {this.visible = !this.visible;}ngOnInit() {}}
如果定义的公共组件在多个文件中被引入,那么需要在单独定义一个**.module.ts文件,然后在父组件所在的模块中引入,否则多次引入组件会报错.
common-component.module.ts
- 如果定义的组件只使用一次,那么只需要在父组件的**.module.ts中申明就行了.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';import { PopupComponent } from "./popup/popup.component";@NgModule({// 导入公共模块imports: [CommonModule],// 申明组件declarations: [PopupComponent],// 到出公共组件exports: [PopupComponent]
})
export class CommonComponent{}
在父组件引入子组建前,先要在父组件的module文件中引入
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {FormComponent} from './form/form.component';
import {ReactiveFormsModule} from '@angular/forms';
import { CommonComponent } from "./component/comon-component.module";@NgModule({declarations: [AppComponent,FormComponent],imports: [BrowserModule,AppRoutingModule,ReactiveFormsModule,CommonComponent],providers: [],bootstrap: [AppComponent]
})
export class AppModule {
}
父组件
form.html
<app-popup bankName="popup" account-id="1" (showPopoup)="show($event)"
(hidePopoup)="hide($event)"><p style="color: tan">我是当前插入的内容p>
app-popup>
form.component.ts
import { Component, OnInit } from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup} from '@angular/forms';@Component({selector: 'app-form',templateUrl: './form.component.html',styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {constructor() {}show(value) {console.log(value)}hide(value) {console.log(value);}ngOnInit() {}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
