还是angularjs2入门1-文件结构分析的源码,将app名称改成basic-step2-component
上篇文章入门1讲到的是只有一个组件,多人团队合作的时候就不方便了,要多个人同时开发组件然后合在一起,就需要多个组件。接下来详细讲解一下怎么修改一下代码。
1.创建多个组件,一个文件可以放一个组件也可以放多个组件
组件1:click-me.component.ts,放入了1个组件click-me
import { Component } from '@angular/core'; @Component({ selector: 'click-me',template: ` <button (click)="onClickMe()">点我!</button> {{clickMessage}}` }) export class ClickMeComponent { clickMessage = ''; onClickMe() { this.clickMessage = '菜鸟教程!'; } }组件2:loop-back.component.ts,放入了1个组件loop-back
import { Component } from '@angular/core'; @Component({ selector: 'loop-back',template: ` <input #Box (keyup)="0"> <p>{{Box.value}}</p> ` }) export class LoopbackComponent { }
组件3:keyup.components.ts,里面有4个组件
import { Component } from '@angular/core'; @Component({ selector: 'key-up1',template: ` <input (keyup)="onKey($event)"> <p>{{values}}</p> ` }) export class KeyUpComponent_v1 { values = ''; /* // without strong typing onKey(event:any) { this.values += event.target.value + ' | '; } */ // with strong typing onKey(event: KeyboardEvent) { this.values += (<HTMLInputElement>event.target).value + ' | '; } } ////////////////////////////////////////// @Component({ selector: 'key-up2',template: ` <input #Box (keyup)="onKey(Box.value)"> <p>{{values}}</p> ` }) export class KeyUpComponent_v2 { values = ''; onKey(value: string) { this.values += value + ' | '; } } ////////////////////////////////////////// @Component({ selector: 'key-up3',template: ` <input #Box (keyup.enter)="values=Box.value"> <p>{{values}}</p> ` }) export class KeyUpComponent_v3 { values = ''; } ////////////////////////////////////////// @Component({ selector: 'key-up4',template: ` <input #Box (keyup.enter)="values=Box.value" (blur)="values=Box.value"> <p>{{values}}</p> ` }) export class KeyUpComponent_v4 { values = ''; }
2.将组件引入模块,修改app.module.ts
import { ClickMeComponent } from './click-me.component';
import { LoopbackComponent } from './loop-back.component';
import {
KeyUpComponent_v1,
KeyUpComponent_v2,
KeyUpComponent_v3,
KeyUpComponent_v4
} from './keyup.components';
declarations修改成
declarations: [ AppComponent,ClickMeComponent,LoopbackComponent,KeyUpComponent_v1,KeyUpComponent_v2,KeyUpComponent_v3,KeyUpComponent_v4,],
3.修改app.component.ts
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html'
})
加上了moduleId和templateUrl,moduleId是为了区分不同的组件,templateUrl是为了放置很多组件的html文件。
4.,创建app.component.html,写入内容
<p> <click-me></click-me> </p> ———————————————————————————————————————————————————————————————————————————— <p> <loop-back></loop-back> </p> ———————————————————————————————————————————————————————————————————————————— <h4>输入信息!</h4> <div><key-up1></key-up1></div> <h4>重复监听keyup事件!</h4> <div><loop-back></loop-back></div> <br><br> <h4>输入更多信息!</h4> <div><key-up2></key-up2></div> <h4>输入信息!按下回车键后完成输入!</h4> <div><key-up3></key-up3></div> <h4>输入信息!按下回车键或点击元素外的区域后完成输入!</h4> <div><key-up4></key-up4></div>可以npm start看一下效果了 原文链接:https://www.f2er.com/angularjs/147975.html