angular8.x父子组件传值和方法【不定时更新,实际用到再补充】

  • 一、父组件向子组件的传入数据

[selected]=”tCbCbglpws” 左侧是名称---右侧是数据

<app-child [selected]="tCbCbglpws"></app-child> <!--父组件中子组件引用-->

// 父组件ts
export class FatherComponent implements OnInit {
    public tCbCbglpws = '这是父组件的数据';
    constructor() {

    }
}

子组件引入Input模块

import { Component, OnInit,Input } from '@angular/core';
export class AppChildComponent implements OnInit {
  @Input() selected: any;  // 通过Input接收父组件传过来的数据selected
  constructor() {

  }
}

appChild子组件在页面直接就能调用接受过来父组件selected的数据

{{selected}}
  • 二、父组件调用子组件方法

父组件

<!--html icon 父组件自己的方法-->
<i class="anticon anticon-plus-circle-o" (click)="showModal()"></i>

<app-child #appChild ></app-child> <!--父组件中子组件引用-->
// 父组件 ts篇章
@ViewChild('appChild') appChild: AppChildComponent;
tCbCbglpws:any;

showModal = () => {
	let size = this.tCbCbglpws.length;
	
	this.appChild.tdBpxm.querySize = 6 + size;// 补位【重复性数据是在请求后删选,需要补位】
	this.appChild.getList(true);
};

子组件

this.queryTdBpxm是继承了分页,这里就不详细说明了。。。。

// ts篇章
getList(): void {
    // ajax请求   
	this._http.getDt(this.queryTdBpxm).subscribe((res: any) => {
		if (res.status === 200) {
			// 重复选择的数据删除,c代表选择,o代表原数据
			this.removeDt(this.selected, res.data.list);
			this.tdBpxmList = res.data.list;
		} else {
			this.msg.error('获取失败');
		}
	});
}


/**
 *
 * @param c 已经陈铺在页面的数据【被选择中的】
 * @param o ajax加载的原数据
 * @author xuhy
 */
removeDt(c: any[], o: any[]) {
	c.forEach(old => {
		var index = o.findIndex(e => {
			return e.zdGuid === old.zdGuid;
		});
		o.splice(index, 1);
	});
}

使用场景如下gif

注意点

发布了206 篇原创文章 · 获赞 49 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/Sicily_winner/article/details/103095853