新聞中心
這篇文章主要為大家展示了“angular4自定義組件的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“angular4自定義組件的示例分析”這篇文章吧。

在 Angular 中,我們可以使用 {{}} 插值語法實現(xiàn)數(shù)據(jù)綁定。
新建組件
$ ng generate component simple-form --inline-template --inline-style # Or $ ng g c simple-form -it -is # 表示新建組件,該組件使用內(nèi)聯(lián)模板和內(nèi)聯(lián)樣式 //會自動為simple-form生成simple-form.component.ts文件,文件中的selector為:app-simple-form,自動添加了app-前綴
輸出:
installing component create src/app/simple-form/simple-form.component.spec.ts // 用于單元測試 create src/app/simple-form/simple-form.component.ts // 新建的組件 update src/app/app.module.ts //Angular CLI 會自動更新 app.module.ts 文件。把新建的組件添加到 NgModule 的 declarations
數(shù)組中
app.module.ts更新后:
@NgModule({
declarations: [
AppComponent,
SimpleFormComponent
],
...
})
export class AppModule { }創(chuàng)建 UserComponent 組件
import { Component } from '@angular/core';
@Component({ //Component 裝飾器來定義組件的元信息
selector: 'sl-user',
template: `
大家好,我是{{name}}
我來自{{address.province}}省,
{{address.city}}市
{{address | json}}
//Angular 內(nèi)置的 json 管道,來顯示對象信息
`, })
//定義組件類
export class UserComponent {
name = 'name';
address = { province: 'province', city: 'city' }
}
//使用構(gòu)造函數(shù)初始化數(shù)據(jù)
export class UserComponent {
name: string;
address: any;
constructor() {
this.name = 'name';
this.address = {
province: 'province',
city: 'city'
}
}
}
//接口使用
interface Address {
province: string;
city: string;
}
export class UserComponent {
name: string;
address: Address;
constructor(){
this.name = 'name';
this.address = {
province: 'province',
city: 'city'
}
}
}定義數(shù)據(jù)接口( TypeScript 中的接口是一個非常靈活的概念,除了可用于對類的一部分行為進行抽象以外,也常用于對「對象的形狀(Shape)」進行描述。)
interface Person {
name: string;
age: number;
}
let semlinker: Person = {
name: 'semlinker',
age: 31
};聲明 UserComponent 組件
// ...
import { UserComponent } from './user.component';//載入
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, UserComponent],//聲明
bootstrap: [ AppComponent ]
})
export class AppModule { }在AppComponent中使用 UserComponent 組件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
//UserComponent 的 selector
`,
})
export class AppComponent {}以上是“angular4自定義組件的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計公司行業(yè)資訊頻道!
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
文章名稱:angular4自定義組件的示例分析-創(chuàng)新互聯(lián)
URL分享:http://www.dlmjj.cn/article/shgjh.html


咨詢
建站咨詢
