angular4组件传值--@Input,@Output,@ViewChild,Subject,路由传值

1. @Input和@Output父子组件传值

    1>  @Input父组件给子组件传值(属性绑定):

          父组件html:

          

<!-- 属性绑定,compareLayers在ng-leaflet-shutter中一定要写@Input引入 -->

<ng-leaflet-shutter #shutterCmp [compareLayers]="compareLayers" [mapOption]="mapOption">

  内容
</ng-leaflet-shutter>

           子组件的ts:

  

@Component({

selector: "ng-leaflet-shutter",

templateUrl: "./shutter-map.component.html",

styleUrls: ["./shutter-map.component.css"]

})

export class ShutterMapComponent implements OnInit, AfterViewInit {

@Input() compareLayers;

@Input() mapOption: any;

            这样父组件的compareLayers和mapOption的值就传到了子组件中

    2>   @Output传值--子组件主动给父组件动态传值(事件绑定),需要@angular/core包下的EventEmitter对象来监听并处理数据子组件定义output:

    

import {Output} from "@angular/core";

@Output() showChange = new EventEmitter();


ngOnInit(){

    this.showChange.emit(this.showValue);

}

 

             父组件html中写入子组件 nc-overlay-panel,通过事件触发eventHandler时间获取子组件传入的值

    

<nc-overlay-panel [panelTitle]="chartPanelTitle" (event)="eventHandler($event)">

</nc-overlay-panel>



eventHandler(showValue){

      console.log(showValue);

}

2.     ViewChildren和ViewChild(父组件主动获取子组件的值),获取摸板中其他组件的元素或者直接调用方法,ViewChid是一 个,ViewChildren是多个,父组件调用子组件NcOverlayPanelComponent中属性,子组件必须是ngAfterViewInit,才能查询到条件


 

<nc-overlay-panel #monthChartPanel class="month-monitor-panel" [panelTitle]="'AQI监测数据'" [show]="true">

   内容

</nc-overlay-panel>




@ViewChild("monthChartPanel") monthChartPanel: NcOverlayPanelComponent;

@ViewChildren(NzMenuItemComponent) menuCmps: QueryList<NzMenuItemComponent>;

        monthChartPanel NcOverlayPanelComponent是子类,即相当于子类创建对象,即可调用(ngAfterViewInit中才能查询到条件)monthChartPanel.属性和方法, menuCmps即代表的是NzMenuItemComponent,在ngAfterViewInit中即可获取       NzMenuItemComponent的元素和方法。

3.   通过Angular2 RxJS Subject应用完成组件之间传值

    


在service中发射User


private userSource: Subject<User>; // 观察者userSource,注册或登录成功后发射当前用户



constructor(private http: HttpClient) {

    this.isLoggedIn = false;

    this.userSource = new Subject<User>();

    this.loginUrl = loginConfig.loginUrl;

}


在service中写一个方法获取存储的user

login(user){

    this.userSource.next(user); //把user发布到subject中

}

在需要使用的地方获取并订阅


get currentUser(): Observable<User> {

    return this.userSource.asObservable();

}


在使用中调用service中的currentUser,订阅获取值



this.loginService.currentUser.subscribe(data => {

    this.currentUser = data;

    console.log(data);

});

4.  路由传值,单个值和对象值

    单个值传值:

import { Router } from '@angular/router';

constructor(

private router: Router

) { }


ngOnInit(){

   this.router.navigate(["taskDetail", 1]);

}

   路由url中:


 

{

    path: "taskDetail/:id",

    component:TaskDetailComponent

},

  获取单个值的方法:


import { ActivatedRoute } from '@angular/router';


constructor(

public activeRoute: ActivatedRoute,

) {}



ngOnInit(){

    this.id = this.activeRoute.snapshot.params['id'];
  
}

      

      对象传值:

       引入的router和单个值相同

this.router.navigate(["../regularCompare"], {

queryParams: {

    compareData: JSON.stringify(对象)

},

    relativeTo: this.route

});

      跳转url:

{

    path: "regularCompare",

    component: RegularCompareComponent

},

      获取对象方法:

      route即activeRoute和单个引入一样



constructor(
    private route:ActivatedRoute
 ) { }


ngOninit(){

    this.route.queryParamMap.subscribe(params => {

       const compareData = JSON.parse(params.get("compareData"));

    })
}

猜你喜欢

转载自blog.csdn.net/qq_34790644/article/details/80191959
今日推荐