我有一个文本,其中有输入。这些输入由Pipe提供(我需要用这些输入替换一些单词)。现在我想在每个输入中写入不同的单词,并将其存储到obj,所以如果我输入前3个输入smth,如红色,绿色,苹果,它存储到对象{ “0”:“红色”, “1”:“绿色”, “2”:“苹果”, }
这是代码
管
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'replacer'})
export class SanitizeHtml implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(data, arg) {
arg.forEach(item => data = data.replace(new RegExp(item, 'g'), '<input type="text" >'));
return this.sanitizer.bypassSecurityTrustHtml(data);
}
}
我猜我需要在管道中挂一些东西,比如
<input type="text" name="{{i}}" ngModel #prix="ngModel" [id]="i">
但它现在不起作用......
我的组件是
@Component({
moduleId: module.id,
selector: 'part2',
template: `
<p>{{values}}</p>
<p>{{abc}}</p>
<div [innerHtml]="itemsSource | replacer: abc"></div>
<button>Ok</button>
<p>Score <input/></p>
<pre>{{f.value | json}}</pre>
`,
providers: [DataService]
})
// @Pipe({name: 'replacer'})
export class Part2Component implements OnInit {
@ViewChildren ('prix') inputs;
public itemsSource: string;
public abc: string[];
constructor(public dataService: DataService) {
}
ngOnInit() {
this.abc = this.dataService.getData3();
this.itemsSource = this.dataService.getData2();
}
}
我使用Dataservice的数据
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
getData2() {
let items3: string = 'I like orange, blue, black, pink, rose, yellow, white, black';
return items3;
}
getData3(){
let items4: string[] = ['black', 'yellow'];
return items4;
}
}
所以,现在我有Picture这个例子,我希望能够输入单词并显示为对象Picture 2 {“0”:“APPLES”, “1”:“绿色”, “2”:“布朗”,}
请帮帮我......
答案 0 :(得分:1)
您可以验证此帖子Equivalent of $compile in Angular 2以使用动态组件(如Angular 1的$ compiler)并在Pipe创建的输入上插入ngModel。解决此问题的其他方法是获取输入值,如下面的代码:
import {Component, OnInit, ViewChildren} from "@angular/core";
import {SanitizeHtml} from "./PipeTeste";
@Component({
selector: 'part2',
template: `
<p>{{values}}</p>
<p>{{abc}}</p>
<div [innerHtml]="itemsSource | replacer: abc"></div>
<button (click)="buttonOk()">Ok</button>
<p>Score <input/></p>
<pre>{{obj}}</pre>
`,
providers: [SanitizeHtml]
})
// @Pipe({name: 'replacer'})
export class Part2Component implements OnInit {
@ViewChildren ('prix') inputs;
public itemsSource: string;
public abc: string[];
public obj: string[];
constructor(public p:SanitizeHtml) {
}
buttonOk() {
let a:any = document.getElementsByClassName('inputValue');
this.obj = [];
for(let i in a){
if(a[i] && a[i].value){
this.obj.push(a[i].value)
}
}
}
ngOnInit() {
this.abc = ['black', 'yellow'];
this.itemsSource = 'I like orange, blue, black, pink, rose, yellow, white, black';
}
}
我希望我帮助过你。