angular2实现子组件之间的实时替换

在实现子组件之间的实时替换之前要学会父子组件之间的传值。具体步骤看:

https://blog.csdn.net/sanlingwu/article/details/80903537

项目的大体结构如下图所示:


其中main组件是board和preview组件的父组件,其中所有值都是在main父组件中获取的,获取到之后再传给子组件board和preview。页面是:


展示的东西要显示在preview里面也就是页面的右边。输入的东西是board组件里面的即页面左边。要达到的效果是在左边输入框输入东西右边对应的东西就跟着变。

1.在main组件里面获取值之后先对其进行处理,利用正则表达式对他进行查找,把要改变的地方加上class(不加id是因为一个页面只允许有一个id,如果右边页面有两个及以上相同的东西使用id就乱了)即:

this. articlemsg = this. test2;
this. previewmsg = this. test2. bcontent;
var re = / \(\( . *?\)\) / g; //正则校验查找返回的结果中带(())的位置.
var flag = this. dedupe( this. previewmsg. match( re)); //对其去重处理
for ( var i = 0; i < this. articlemsg. rllist. length; i++) {
if ( flag[ i] == this. articlemsg. rllist[ i]. rlsymbol) {
var re = RegExp( " \\ ( \\ (" + this. articlemsg. rllist[ i]. rlsymbol + " \\ ) \\ )", "g"); //查找替换,中间是查找的东西。下面replace是把找到的re换成加class标签的。
this. previewmsg = this. previewmsg. replace( re, ( '<span class="' + this. articlemsg. rllist[ i]. rlcode + '">' + this. articlemsg. rllist[ i]. rlname + '</span>'));
this. articlemsg. bcontent = this. articlemsg. bcontent. replace( re, ( '<span class="' + this. articlemsg. rllist[ i]. rlcode + '">' + this. articlemsg. rllist[ i]. rlname + '</span>'));
}
}

数组去重函数:

扫描二维码关注公众号,回复: 4335133 查看本文章
dedupe( array) {
return Array. from( new Set( array));
}

test2是一个测试数据,结构如下:

test2 = {
"docid" : "123",
"cpcode" : "1000",
"bcontent" : "<p>1111我们公司董事长是((president_name))……</p><p>1111我们公司股东是((stockholder_name))……</p>",
"rllist" : [
{
"rlcode" : "5111",
"rlname" : "111董事长姓名",
"rlsymbol" : "((president_name))",
"rlnote" : "文档中所有董事长姓名将被替换为输入内容"
},
{
"rlcode" : "5112",
"rlname" : "股东姓名",
"rlsymbol" : "((stockholder_name))",
"rlnote" : "文档中所有股东姓名将被替换为输入内容"
}
]
}

再把加完标签的值即this.previewmsg传给preview组件。这样preview组件展示在页面上就是加class标签的。

2.在board组件里面写个函数实时监控输入框的输入情况。即:

searchMonitorList( event, id) {
$( "." + id). html( event);
}

html里面:(页面的加载是痛殴)


searchMonitorList函数传的是输入框的输入值和此输入框的id。输入框的id对应之前在main组件里面加的class标签。通过$("." +id).html(event)就可以看见变化。event是输入框的值。

猜你喜欢

转载自blog.csdn.net/khh8023lyf/article/details/81010732