@Input和@Output


  1. 描述
    • 在父子指令或者组件之间共享数据
  2. @Input
    • 从父组件中把数据发送到子组件中
    • 通过@Input装饰过的变量可以作为共享变量在父子组件之中使用,如下:
      • 子组件的ts文件中定义一个@Input类型的string变量item,默认值为空字符串
      • 查看代码
        import { Component, OnInit,Input, SimpleChanges } from '@angular/core';
        
        @Component({
          selector: 'app-ly-input-child',
          templateUrl: './ly-input-child.component.html',
          styleUrls: ['./ly-input-child.component.css']
        })
        export class LyInputChildComponent implements OnInit {
        
          // 使用@Input()来装饰item属性
          @Input() item='';
          constructor() { }
        
          ngOnInit(): void {
          }
        
          ngOnChanges(changes: SimpleChanges): void {
            console.log('onChange====>'+changes['item'].previousValue+'|||||CurrentValue='+changes['item'].currentValue);
          }
        
        }
      • 子组件的模板文件中作为插值字符串使用
      • 查看代码

        ly-input-child works! Today's Item:{{item}}

      • 父组件的ts文件中定义个名叫currentItem的变量并且赋值
      • 查看代码
        import { Component, OnInit } from '@angular/core';
        
        @Component({
          selector: 'app-ly-input-parent',
          templateUrl: './ly-input-parent.component.html',
          styleUrls: ['./ly-input-parent.component.css']
        })
        export class LyInputParentComponent implements OnInit {
          // 定义CurrentItem,用于和子组件中的@input类型的item变量绑定
          currentItem = 'Liye in pain';
          constructor() { }
        
          ngOnInit(): void {
          }
        
        }
      • 在父组件的模板文件中引入子组件的模板文件,并且使用属性绑定把子组件的item属性绑定到父组件的currentItem属性上(记得在app.component.ts中导入FromModule组件哦,否则ngModel编译会报错的)
      • 查看代码
        
        
        -------------------------------------------------------------------
        ly-input-parent works! 
        
        {{currentItem}}
      • 通过@Input()装饰器,angular把currentItem的值传给了子组件的item,然后在子组件上就可以渲染为字符串Liye in pain
  3. @Output

搜索

复制