组件间传值

定义子组件:

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

 

 
 
 
 
 
posted @ 2018-05-06 22:13  雨夜稻草  阅读(320)  评论(0编辑  收藏  举报