Я новичок в angular и еще не успокоился. У меня есть компонент, который я создал на основе примера на веб-сайте Angular Material:
https://material.angular.io/components/chips/overview
html для компонента выглядит следующим образом :
<mat-form-field class="full-width-field">
<mat-chip-list #chipList
aria-label="Tags">
<mat-chip *ngFor="let tag of tags"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(tag)">
{{tag}}
<mat-icon matChipRemove
*ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Tags"
#tagInput
[formControl]="tagCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
(matChipInputTokenEnd)="add($event)"
required>
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete"
(optionSelected)="selected($event)">
<mat-option *ngFor="let tag of filteredTags | async"
[value]="tag">
{{tag}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
И компонент выглядит так:
import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import {
MatAutocomplete,
MatChipInputEvent,
MatAutocompleteSelectedEvent
} from "@angular/material";
import { FormControl } from "@angular/forms";
import { Observable } from "rxjs";
import { COMMA, ENTER } from "@angular/cdk/keycodes";
import { startWith, map } from "rxjs/operators";
import { TagService } from "@services";
@Component({
selector: "app-tags",
templateUrl: "./tags.component.html",
styleUrls: ["./tags.component.scss"]
})
export class TagsComponent implements OnInit {
@ViewChild("tagInput", { static: false }) tagInput: ElementRef<
HTMLInputElement
>;
@ViewChild("auto", { static: false }) matAutocomplete: MatAutocomplete;
visible = true;
selectable = true;
removable = true;
separatorKeysCodes: number[] = [ENTER, COMMA];
tagCtrl = new FormControl();
filteredTags: Observable<string[]>;
tags: string[] = [];
allTags: string[] = [];
constructor(private tagService: TagService) {
this.filteredTags = this.tagCtrl.valueChanges.pipe(
startWith(null),
map((tag: string | null) =>
tag ? this._filter(tag) : this.allTags.slice()
)
);
}
ngOnInit() {
this.tagService
.list()
.subscribe(tags => (this.allTags = tags.map(m => m.id as string)));
}
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our tag
if ((value || "").trim()) {
this.tags.push(value.trim());
}
// Reset the input value
if (input) {
input.value = "";
}
this.tagCtrl.setValue(null);
}
remove(tag: string): void {
const index = this.tags.indexOf(tag);
if (index >= 0) {
this.tags.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
this.tags.push(event.option.viewValue);
this.tagInput.nativeElement.value = "";
this.tagCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allTags.filter(
tag => tag.toLowerCase().indexOf(filterValue) === 0
);
}
}
Я хочу добавить mat-error , поэтому я попробовал это:
<mat-error *ngIf="tagCtrl.errors?.required && (tagCtrl.touched && tagCtrl.dirty)">This is an error</mat-error>
Но это не сработало. Обычно при использовании реактивных форм я использую [formControlName]
, но, поскольку это общий компонент, он не принадлежит форме, поэтому я думаю, поэтому они используют [formControl]
??? Кто-нибудь может мне помочь?