码迷,mamicode.com
首页 > 其他好文 > 详细

Angular8入门-3 创建组件

时间:2020-02-24 00:07:18      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:注入   创建组   export   组件   html   private   png   nbsp   tle   

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

技术图片

 

Angular8入门-3 创建组件

标签:注入   创建组   export   组件   html   private   png   nbsp   tle   

原文地址:https://www.cnblogs.com/zhaogaojian/p/12355145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!