• 组件间传值


    定义子组件:

    1)ionic g compoment myHeader

    引用组件:

    在app.module.ts中

    import { MyHeadComponent} from '../components/my-head/my-head';

    declarations: [MyHeadComponent ]
    父组件传值给子组件 -@Input (父组件主动)
    1)父组件中:
    <app-header [title]="title"></app-header>
    ts中this.title ="xxxxx";
    2)子组件中:
    <div>{{title}}</div>
    import { Component , OnInit ,Input} from '@angular/core';
    @Input() title:string;
     
     子组件传值给父组件 -EventEmitter(子组件主动)
     1)子组件中:
    import { Component, Output,EventEmitter } from '@angular/core';
    @Output() private outer=new EventEmitter<Boolean>();
    Codeclose(){
        this.outer.emit(false);//通过传传参方式,将参数传给父组件
    }
    2)父组件中:
    <wei-code [user]="user" (outer)="close($event)"></wei-code>
    close(state: boolean) {
      this.codeState = state;//state的值即为子组件传来的false
    }
    通过事件传值:
    1)有亲属关系
     
     
     
    2)无亲属关系
    数据服务ProductService:
    import { Injectable , EventEmitter} from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ProductService {
        public eventEmit: any; 
            constructor() { 
            this.eventEmit = new EventEmitter<any>();
        }
    }
    A组件按钮触发传值:
    <button (click)="giveTo()">传递数据</button>
    import { Component, OnInit } from '@angular/core';
    import { ProductService } from '../../services/product.service';
    @Component({
      selector: 'app-silder',
      templateUrl: './silder.component.html',
      styleUrls: ['./silder.component.sass']
    })
    export class SilderComponent implements OnInit {
      name ;
      constructor(private ProductService: ProductService) { }
    
      ngOnInit() {
      }
      giveTo(){
            this.name = '短袖'
            this.ProductService.eventEmit.emit(this.name);
        }
    }
    B组件接收A组件的值:
    import { Component, OnInit } from '@angular/core';
    import { ProductService } from '../../services/product.service';
    @Component({
      selector: 'app-start',
      templateUrl: './start.component.html',
      styleUrls: ['./start.component.sass']
    })
    export class StartComponent implements OnInit {
      name;
      constructor(private ProductService:ProductService) { }
      ngOnInit() {    
              this.ProductService.eventEmit.subscribe((value: any) => {
              this.name = value;
              console.log(this.name);
      });
            
      }
    }
     
     
     
     
     
  • 相关阅读:
    Redis中统计各种数据大小的方法
    Redis配置文件详解
    Redis服务器的启动过程分析
    在Mac OS上安装Vagrant和Docker的教程
    使用Redis实现用户积分排行榜的教程
    Redis教程(一):Redis简介
    Redis教程(二):String数据类型
    Redis教程(四):Hashes数据类型
    Redis教程(六):Sorted-Sets数据类型
    Redis教程(八):事务详解
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/9000012.html
Copyright © 2020-2023  润新知