组件传值

1. 父向子组件传值,和传递方法

父组件 app-home 

子组件 app-header

// --- app-home.html 页面

<app-header [msg]="msg" [run]='run' [getDataFromChild]="getDataFromChild"></app-header>


// --- app-home.ts 

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './app-home.html',
  styleUrls: ['./app-home.css']
})
export class HomeComponent implements OnInit {

  public msg="我是home组件的msg";

  constructor() { }

  ngOnInit() {
  }

  run(){

    alert('这是home组件的run方法');
  }

  getDataFromChild(childData){  /*父组件*/
    alert(childData+"1111");
  }

}


// --- app.header.ts 页面

import { Component, OnInit,Input} from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './app-header.html',
  styleUrls: ['./app-header.css']
})
export class FooterComponent implements OnInit {

  @Input()  msg;


  @Input()  run;  /*接收父组件传过来的run方法*/

  @Input()  getDataFromChild; 


  public msginfo='这是子组件的数据';

  constructor() { }

  ngOnInit() {
  }

  sendParent(){  /*子组件自己的方法*/
      this.getDataFromChild(this.msginfo);  /*子组件调用父组件的方法*/

  }

}

1.2 子组件用广播方式调用父组件方法

// --- app-home.html

<app-footer [msg]="msg" [run]='run' (toparent)="getDataFromChild"></app-footer>

// --- app-home.ts 

import { Component, OnInit } from '@angular/core';
import {Http,Jsonp} from "@angular/http";
@Component({
  selector: 'app-news',
  templateUrl: './app-home.html',
  styleUrls: ['./app-home.css']
})
export class NewsComponent implements OnInit {
   public msg="msg";
   public name="张三";

   public list=[];
  constructor(private http:Http,private jsonp:Jsonp) { }

  ngOnInit() {
  }

  getDataFromChild(childData){  /*父组件*/
    alert(childData+"1111");
  }
}

//--- app-header.ts

import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './app-header.html',
  styleUrls: ['./app-header.css']
})
export class HeaderComponent implements OnInit {

   @Input()  msg:string;  /*通过 Input  接收父组件传过来的msg*/

   @Input()  name:string; 


   //EventEmitter实现子组件给父组件传值

   @Output() toparent=new EventEmitter();

  constructor() { }
  ngOnInit() {}

  //requestData

  requestData(){

    //调用父组件的方法请求数据

    this.toparent.emit('这是子组件的值');
  }

}

2. 父组件获取子组件值

// app-home.html

<app-header #header></app-header>

// app-home.ts

//ViewChild
import { Component, OnInit, ViewChild } from "@angular/core";

@Component({
  selector: "app-home",
  templateUrl: "./app-home.html",
  styleUrls: ["./app-home.css"]
})
export class ProductComponent implements OnInit {
  @ViewChild("header") header; /*定义子组件 注意括号里面的东西和 #header 对应起来  */

  constructor() {}

  ngOnInit() {}

  getChildData() {
    // this.header.run();   /*执行子组件的方法*/

    alert(this.header.msg); /*获取子组件的数据*/

    //  alert(this.header.name);

    this.header.name = "我是父组件改变后的cart name";
  }
}

// app-header.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-header",
  templateUrl: "./app-header.html",
  styleUrls: ["./app-header.css"]
})
export class CartComponent implements OnInit {
  constructor() {}

  public msg = "我是子组件的数据";

  public name = "子组件";

  ngOnInit() {}

  run() {
    alert("这是子组件的方法11");
  }
}

路由之间传参

在网上找到一个不错的写的,分享给大家:

一般我们页面跳转传递参数都是这样的格式:

http://angular.io/api?uid=1&username=moon

但是在SPA单页应用中却是下面的结果居多【初级视频都是这样敷衍的】

http://angular.io/api/1/moon

一、 地址栏传参

实现从product页面跳转到product-detail页面

1:在app-routing.module.ts中配置路由。

const routes: Routes = [
{
    path: 'product',
    component: ProductComponent,
 },
 {
    path: 'product-detail',
    component: ProductDetailComponent,
  }
];

2:在app-routing.module.ts中配置路由。

constructor(
    private router: Router,   //这里需要注入Router模块
){}
 
jumpHandle(){
    //这是在html中绑定的click跳转事件
    this.router.navigate(['product-detail'], {
        queryParams: {
            productId: '1',
            title: 'moon'
        }
    });
}


3:在product-detail.ts中获取传递过来的参数productId、title

constructor(
    private activatedRoute: ActivatedRoute,   //这里需要注入ActivatedRoute模块
) {
    activatedRoute.queryParams.subscribe(queryParams => {
        let productId = queryParams.productId;
        let title = queryParams.title;
    });
}


二、 在查询中传递参数

 



//传递数据
<a [routerLink]="['/stock']" [queryParams]="{id: 1}">股票详情</a>
// http://localhost:4200/stock?id=1



// 接受参数
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private routeInfo: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.queryParams['id'];
    }
    
}

三、 在路径中传递参数

//修改配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent},
  {path: 'stock/:id', component: StocksComponent },
  {path: '**', component: ErrorPageComponent }
];


//传递数据
...
<a [routerLink]="['/stock', 1]">股票详情</a>
// http://localhost:4200/stock/1



//接受参数
...
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private activedRoute: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.activedRoute.snapshot.params['id'];
    }
    
}

使用snapshot快照的方式传递数据,因为初始化一次,路由到自身不能传递参数,需要使用订阅模式。

this.activedRoute.params.subscribe((params: Params) => this.stockId = params['id']);

 

四、在路由中配置

//路由配置配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent, data: {title: 'Index Page'}},
  {path: 'stock/:id', component: StocksComponent, data: {title: 'Stock Page'}},
  {path: '**', component: ErrorPageComponent, data: {title: 'Stock Page'}}
];

//接受参数
this.title = this.routeInfo.snapshot.date[0]['title'];