樣式封裝&組件間通信

關于樣式

angular 可以將樣式封裝在組件本身中,不會影響其他組件的樣式(默認)Angular 會修改組件的 CSS 選擇器,使它們只應用于組件的視圖,不影響應用程序中的其他元素。(React 使用 css module 實現(xiàn)樣式隔離)會將修改了選擇器后的 css 樣式添加到 head 中。

這個樣式的作用域是可以修改的,也可以修改為組件中的樣式影響全局中匹配到的其他元素,以及配置為 ShadowDOM 模式

父組件 -> 子組件

子組件定義@Input 屬性;父組件傳遞自己的數(shù)組給子組件

子組件 -> 父組件

子組件定義 @Output 屬性。

它是一個 EventEmitter 的實例

@Output() public onsubmit = new EventEmitter<number>();
@Output() public cancel = new EventEmitter<void>();

調(diào)用.emit(data)傳遞 data 給父組件

父組件在使用子組件的地方定義一個方法,該方法的參數(shù),就是子組件提交出來的數(shù)據(jù)

<!-- 注意:模版中如果是eventEmitter的示例則$event是我們emit的數(shù)據(jù);如果是原聲事件則是Event實例 -->
<app-child (onsubmit)="onUpdate($event)"></app-child>
public onUpdate(num: number) {
   console.log(num);
}

@ViewChild

在父組件中通過@ViewChild 選中子組件,可以在父組件的nhAfterViewInit中可以拿到子組件的示例,就可以訪問子組件的屬性和方法

import { AfterViewInit, ViewChild } from "@angular/core";
import { Component } from "@angular/core";
import { CountdownTimerComponent } from "./countdown-timer.component";

@Component({
  selector: "app-countdown-parent-vc",
  template: `
    <h3>Countdown to Liftoff (via ViewChild)</h3>
    <button (click)="start()">Start</button>
    <button (click)="stop()">Stop</button>
    <div class="seconds">{{ seconds() }}</div>
    <app-countdown-timer></app-countdown-timer>
  `,
  styleUrls: ["../assets/demo.css"]
})
export class CountdownViewChildParentComponent implements AfterViewInit {
  @ViewChild(CountdownTimerComponent)
  private timerComponent!: CountdownTimerComponent;

  seconds() {
    return 0;
  }

  ngAfterViewInit() {
    this.seconds = () => this.timerComponent.seconds;
  }

  start() {
    this.timerComponent.start();
  }
  stop() {
    this.timerComponent.stop();
  }
}

?? 父組件的模版中定義模版變量(#變量名)

import { Component } from "@angular/core";
import { CountdownTimerComponent } from "./countdown-timer.component";

@Component({
  selector: "app-countdown-parent-lv",
  template: `
    <h3>Countdown to Liftoff (via local variable)</h3>
    <button (click)="timer.start()">Start</button>
    <button (click)="timer.stop()">Stop</button>
    <div class="seconds">{{ timer.seconds }}</div>
    <app-countdown-timer #timer></app-countdown-timer>
  `,
  styleUrls: ["../assets/demo.css"]
})
export class CountdownLocalVarParentComponent {}

局限就是只能在父組件的模板中訪問子組件的所有屬性和方法。父組件本身的代碼對子組件沒有訪問權。

跨組件

service 來實現(xiàn)

父組件和它的子組件共享同一個服務

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容