【发布时间】:2017-09-09 04:12:52
【问题描述】:
我正在尝试向我的 Angular Web 应用程序添加一个芯片组件。它是用 Typescript、HTML 和 CSS 文件编写的。
我已经苦苦挣扎了几个星期,试图让它正确,但没有找到正确的解决方案。
这是一个带有我当前代码的 Plunkr: https://plnkr.co/edit/zvEP9BOktwk6nBojsZQT?p=catalogue
更新:我已经编辑了我的代码以反映我正在读取一个字符串数组的输入,称为选定的。我正在输出一个名为 code 的字符串数组。
下面是我正在使用的代码:
import {
Component, Input, HostBinding, ElementRef, ViewChild, HostListener, EventEmitter, Output, OnInit, SimpleChanges,
OnChanges, QueryList, TemplateRef, ContentChildren, Directive
} from '@angular/core';
import {ControlValueAccessor} from '@angular/forms';
import {Subject} from "@reactivex/rxjs/dist/es6/Subject";
@Component({
selector: 'chips',
templateUrl: './chips.component.html',
styleUrls: ['./chips.component.scss']
})
export class ChipsComponent implements ControlValueAccessor, OnInit{
@Output() code: string[];
@Input() type = 'text';
@Input() duplicates = false;
@Input() selected: any[];
chips: ['chip1', 'chip2', 'chip3']
chipItemList: any[];
constructor() {
}
ngOnInit() {
console.log("selected in chips component ngOnInit(): " + this.selected);
console.log("code in chips component ngOnInit: " + this.code);
}
addChip($event){
this.selected.push($event.target.value)
$event.target.value = '';
}
/*addChip(addSelectedCode) {
//this.newChips.next(this.addCode);
console.log("addCode in chips component addChip(): " + this.addSelectedCode);
if (!this.chip || !this.duplicates && this.selected.indexOf(this.chip) !== -1) return;
this.selected.push(this.chip);
this.chip = null;
this.propagateChange(this.selected);
this.selectedCodeOutput = this.addSelectedCode;
console.log("selectedCodeOutput in chips component: " + this.selectedCodeOutput);
} */
remove(index: number) {
//this.addSelectedCode.splice(index, 1);
this.propagateChange(this.selected);
this.selectedCodeOutput = this.addSelectedCode;
}
/*
Form Control Value Accessor
*/
writeValue(value: any) {
if (value !== undefined) this.selected = value;
}
propagateChange = (_: any) => {
};
registerOnChange(fn: any) {
this.propagateChange = fn;
}
registerOnTouched() {
}
}
我认为问题在于我无法从父模板调用我的子组件。
有没有人有任何有用的建议让芯片组件添加芯片?
谢谢!
【问题讨论】:
-
如果 selectedCodeOutput 是您的 @Output(),您为什么要尝试将其记录到 ngOnInit() 函数中?你在那里看到什么类型的价值?通常当创建一个输出与父组件对话时,他们通常将它们设置为 Angular 的事件发射器并发射某种类型。
-
感谢您的回复。我正在尝试记录它以查看它包含的内容。它实际上甚至没有在我的芯片组件中使用 ngOnInit。我尝试使用 EventEmitter,但没有产生预期的结果。
-
你有没有把你的chipsComponent添加到app模块的声明数组中?当您使用@Output() 时,它基本上意味着孩子正在提醒父母任何变化。在 service-alert 组件中,您正在使用其选择器“chips”来调用子级。一个错误是您正在收听 (addSelectedCode) 但您没有将其用于任何特定目的。当孩子有输出时,您会想做一些工作,最好是使用函数。像这样 (addSelectedCode)="onSelectedCodeAddition($event)"。另外,你是否在 app 模块中声明了 service-alert 组件?
-
您到底想做什么?您没有清楚地解释问题。您的 plunker 没有任何有用的代码,它只是显示您好消息。无法正确解释您的问题。请详细说明您的问题。
-
@VikhyathMaiya 我正在尝试将芯片添加到我的 Web 应用程序中。对不起,这是我第一次与 Plunker 合作。这是一个芯片演示的链接,类似于我正在尝试做的事情:material.angularjs.org/latest/demo/chips希望有帮助。如果您对我正在做的事情有任何具体问题,请告诉我...
标签: html css angular typescript