zoukankan      html  css  js  c++  java
  • 组件间传值

    定义子组件:

    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);
      });
            
      }
    }
     
     
     
     
     
  • 相关阅读:
    Codeforces 741D 【Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths】
    Codeforces 235C 【Cyclical Quest】
    UOJ #62.【UR #5】怎样跑得更快
    luoguP3648 [APIO2014]序列分割
    luoguP4782 [模板]2-SAT问题
    原博客已废弃
    个数可变的参数收藏
    新的一年开始。
    文件上传下载总结
    模板模式学习(转)
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/9000012.html
Copyright © 2011-2022 走看看