Angular8.X 組件理解


組件封裝的意義:

  需要重用或者簡化邏輯。

命令行創建指令:
  ng generate/g component/c components/componentName.

ps: 可以手動加入index.ts進一步方便導入組件,以及隔離內部變化對外部的影響。

  目錄結構如下:

  -> components

    index.ts

      index.ts代碼:

export * from './child'

    ->child

      index.ts 

         index.ts代碼:

export * from './child.component';

      child.component.html

      child.component.less

      child.component.spec.ts

      child.component.ts

 

父子組件傳值:

  父向子組件傳值:

  父組件代碼:

    app.component.ts

import { Component } from '@angular/core';

@Component({   
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
 //父組件定義userName將傳值給子組件 userName: string = 'zs'; }

    app.component.html

<div>
 <!-- 在引用子組件標簽中以屬性綁定方式將userName傳遞給子組件 -->
  <!-- 當傳遞一個字符串時寫法: user='zs' -->
  <app-child user="zs"></app-child>
  <app-child [user]="userName"></app-child>
</div>

  子組件接收代碼:

    child.component.ts

// 在子組件里面引入Input,然后執行@Input裝飾器將變量接收
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.less'] }) export class ChildComponent implements OnInit { @Input() user; constructor() { } ngOnInit() { } }

  子向父組件傳值:

  子組件代碼:

    child.component.ts

// 引入Output,EvnentEmitter模塊,通過裝飾器@Output實例化EventEmitter
import { Component, OnInit, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.less'] }) export class ChildComponent implements OnInit { userName: string = 'zs';   // 實例化 EventEmitter @Output() childEvent = new EventEmitter(); constructor() { } ngOnInit() { }   handleEvent() {   向子組件通過EventEmitter實例的emit方法以參數的形式映射出userName this.childEvent.emit(this.userName) } }

    child.component.html

<!-- 在子組件中觸發映射事件handleEvent,向父組件傳值 -->
<p (click)='handleEvent()'>child works!</p>

  父組件代碼:

    app.component.html

<div>
  <!-- 父組件中以事件綁定的形式綁定子組件中 EventEmitter的實例,觸發getChildEvent方法,通過傳參接收子組件傳遞的數據 --> <app-child (childEvent)="getChildEvent($event)"></app-child> </div>

    app.component.ts

import { Component } from '@angular/core';

@Component({   
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {

  getChildEvent(userName) {
  // 打印子組件傳遞的數據
    console.log(userName);

  }

}

  

 

      

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM