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);

  }

}

  

 

      

  

转载于:https://www.cnblogs.com/eightabs/p/11454663.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值