Angular学习笔记第三章——创建组件
生活随笔
收集整理的這篇文章主要介紹了
Angular学习笔记第三章——创建组件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Angular學習筆記三——創建組件
1.創建組件
通過以下命令,創建新組件:
ng generate component users創建成功后,新組件構成如下:
新組件創建成功后,會被自動添加到app.module.ts中:
新組件users.component.ts自動生成的代碼如下:
import { Component, OnInit } from '@angular/core';@Component({selector: 'app-users',templateUrl: './users.component.html',styleUrls: ['./users.component.css'] }) export class UsersComponent implements OnInit {constructor() { }ngOnInit(): void {}}| @Component | 一個裝飾器函數,用于為組件指定Angular所需的元數據。 |
| selector | 組件的選擇器(CSS元素選擇器) |
| templateUrl | 組件模板文件的位置 |
| styleUrls | 組件私有CSS樣式表文件的位置 |
| CSS元素選擇器app-users | 用來在父組件的模板中匹配HTML元素的名稱,以識別出該組件 |
| ngOnInit | 生命周期鉤子,Angular在創建完組件后,就會立刻調用該函數,是放初始化邏輯的好地方 |
| export | 表明該組件類可以被導出,以便在其他地方導入它 |
2.添加屬性
在users.component.ts類中添加user屬性:
export class UsersComponent implements OnInit {user = '漢堡包';constructor() { }ngOnInit(): void {}}在users.component.html中綁定user屬性:
{{user}}將users組件添加到,AppComponent的模板中,即可顯示內容。
app.component.html:
3.雙向數據綁定
創建用戶類user.ts:
export class User {id: number = 0;name: string = ''; }在用戶組件users.component.ts中使用該用戶類:
import { Component, OnInit } from '@angular/core'; import { User } from '../../model/user';@Component({selector: 'app-users',templateUrl: './users.component.html',styleUrls: ['./users.component.css'] }) export class UsersComponent implements OnInit {user: User = {id: 1,name: '漢堡包'}constructor() { }ngOnInit(): void {}}在頁面顯示users.component.html:
<div><span>id:</span>{{user.id}}</div> <div><label>name:</label><input [(ngModel)]="user.name"> </div>在頁面添加輸入框來編輯用戶的名字。當用戶輸入名字時,輸入框可以同時顯示和修改name屬性。即數據從組件類流出到屏幕,并且從屏幕流回到組件類。這叫做雙向數據綁定。
但是, [(ngModel)]在默認情況下是不可用的,它屬于FormsModule模塊,需要在app.module.ts中添加該模塊。
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms';import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { UsersComponent } from './users/users.component';@NgModule({declarations: [AppComponent,UsersComponent],imports: [BrowserModule,AppRoutingModule,FormsModule],providers: [],bootstrap: [AppComponent] }) export class AppModule { }刷新頁面:
總結
以上是生活随笔為你收集整理的Angular学习笔记第三章——创建组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无人机算法之PID
- 下一篇: EPSON TM U220串口打印机乱码