Angular 父子組件傳值
阿新 • • 發佈:2019-02-04
沒有 新聞組 不能 引入 樣式 自己的 and alt ima
Angular 父子組件傳值 @Input @Output @ViewChild
新建一個頭部組件 newsheader
在主組件引用 news 組件,在news組件添加 newsheader 組件。
設置newsheader組件樣式
設置newsheader組件的內容,添加一個class屬性
<h2 class="header">這是一個頭部組件</h2>
如果需要全局設置,則在 style.css 中設置。
如果單獨設置自己的,則在自己組件的css中設置。
此項目案例設置全局的。
/* You can add global styles to this file, and also import other style files*/ .header{ height: 44px; line-height: 44px; text-align: center; background-color: #000; color: #fff; text-align: center; }
把新聞頁面的數據傳給頭組件(父組件向子組件傳值)
首先在新聞界組件定義一個數據(在父組件定義一個數據)
在父組件中創建一個變量,用於傳遞給子組件:
public message = "這是新聞組件的MSG"
這個 message 屬性屬於新聞組件(父組件),我們可以在新聞組件上打印出來。
<app-newsheader></app-newsheader> <hr> 這是新聞組件 ----- {{message}} <hr> <br>
在頭部組件(子組件)中並沒有定義 message 屬性,我們在頭部(子組件)是拿不到數據的,他們數據不能共享,因此我們需要通過父組件把需要的值(message)傳給子組件。
1.父組件調用子組件的時候傳入數據
<app-newsheader [msg]="message"></app-newsheader>
2.子組件引入 Input 模塊
import { Component, OnInit,Input } from ‘@angular/core‘;
3.接收父組件傳進的數據
@Input() msg:string; /**通過Input接收父組件傳進的msg */
4.在頭部(子組件)使用父組件傳進的數據 msg
<h2 class="header">這是一個頭部組件 -- {{msg}}</h2>
Angular 父子組件傳值