Angular8入門-3 創建組件


1、使用命令創建登錄組件

ng  g  component  login

 2、直接生成組件

 3、也自動添加組件定義到如下位置

4、下面是關鍵

<div class="header" (click)="test()">{{info}}</div>
<app-login><app-login>
<router-outlet></router-outlet>

要注意,這里要和自定義組件中的selector一致

 不要寫成<Login>

5、添加一個自定義屬性

 6、修改login頁面

<p>{{info}}</p>

 7、現在通過點擊父組件修改子組件狀態,使用ViewChild方式

import { Component, ViewChild } from '@angular/core';
import { LoginComponent } from './login/login.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
  
})

export class AppComponent {
  @ViewChild(LoginComponent) // 使用viewChild導入引用
  private loginComponent: LoginComponent;   // 將子組件注入到私有屬性

  title = 'ngstudy';
  info="hello world1";
  @ViewChild('app-login') login: any;
  test() {
    this.info="hello world2";
    console.log(this.login);
    this.loginComponent.info="已登錄";
  } 
}

注意@ViewChild定義位置

8、現在點擊HelloWorld


免責聲明!

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



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