Я хочу сделать настраиваемый компонент в Angular, чтобы заставить пользователя заполнить его. Я видел множество решений, но с использованием кода TypeScript, есть ли способ сделать это с частью HTML, не делая этого с TS
, например:
<mycustom-component required ></mycustom-component>
Обновление:
Ниже мой код. Я использовал mat-select с настраиваемым поиском, затем я вызываю селектор в другом месте в моем проекте, в некоторых местах я хочу, чтобы он требовался, а в других - нет, поэтому я хочу, чтобы требуемое свойство было в селектор компонентов не находится в самом компоненте
мой код
Код TS :
import { Component, OnInit, ViewChild,AfterViewInit, OnDestroy, Output, Input,EventEmitter } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MyCustomComponentDto,MyCustomComponentServiceProxy } from '@shared/service-proxies/service-proxies';
import { ReplaySubject, Subject } from 'rxjs';
import { MatSelect } from '@angular/material';
import { finalize,take, takeUntil } from 'rxjs/operators';
import { SharedService } from '@app/shared.service';
@Component({
selector: 'app-lkp-myCustomComponent',
templateUrl: './lkp-myCustomComponent.component.html',
styleUrls: ['./lkp-myCustomComponent.component.css']
})
export class LkpMyCustomComponentComponent implements OnInit {
/** list of myCustomComponents */
public myCustomComponents: MyCustomComponentDto[] = [];
/** control for the selected myCustomComponent for multi-selection */
public myCustomComponentMultiCtrl: FormControl = new FormControl();
/** control for the MatSelect filter keyword multi-selection */
public myCustomComponentMultiFilterCtrl: FormControl = new FormControl();
/** list of myCustomComponents filtered by search keyword */
public filteredMyCustomComponentsMulti: ReplaySubject<MyCustomComponentDto[]> = new ReplaySubject<MyCustomComponentDto[]>(1);
@ViewChild('multiSelect', { static: true }) multiSelect: MatSelect;
/** Subject that emits when the component has been destroyed. */
protected _onDestroy = new Subject<void>();
myValue=0;
constructor(public _myCustomComponentService:MyCustomComponentServiceProxy,
public sharedService: SharedService) {
}
async ngOnInit() {
this.getAllMyCustomComponents(0);
this.sharedService.fillMyCustomComponent =this.getAllMyCustomComponents.bind(this);
}
ngAfterViewInit() {
this.setInitialValue();
}
ngOnDestroy() {
this._onDestroy.next();
this._onDestroy.complete();
}
/**
* Sets the initial value after the filteredMyCustomComponents are loaded initially
*/
protected setInitialValue() {
this.filteredMyCustomComponentsMulti
.pipe(take(1), takeUntil(this._onDestroy))
.subscribe(() => {
// setting the compareWith property to a comparison function
// triggers initializing the selection according to the initial value of
// the form control (i.e. _initializeSelection())
// this needs to be done after the filteredMyCustomComponents are loaded initially
// and after the mat-option elements are available
this.multiSelect.compareWith = (a: MyCustomComponentDto, b: MyCustomComponentDto) => a && b && a.id === b.id;
});
}
protected filterMyCustomComponentsMulti() {
if (!this.myCustomComponents) {
return;
}
// get the search keyword
let search = this.myCustomComponentMultiFilterCtrl.value;
if (!search) {
this.filteredMyCustomComponentsMulti.next(this.myCustomComponents.slice());
return;
} else {
search = search.toLowerCase();
}
// filter the myCustomComponents
this.filteredMyCustomComponentsMulti.next(
this.myCustomComponents.filter(myCustomComponent => myCustomComponent.myCustomComponentArabicName.toLowerCase().indexOf(search) > -1)
);
}
@Output() change: EventEmitter<any> = new EventEmitter<any>();
@Input() selectedMyCustomComponent: any;
actualChange(event){
this.selectedMyCustomComponent = event.value;
this.change.emit(this.selectedMyCustomComponent);
}
getAllMyCustomComponents(myCustomComponentId:number){
//return setTimeout(() => resolve("juraj2"), 2000);
this._myCustomComponentService
.getAllList()
.pipe(
finalize(() => {
this.filteredMyCustomComponentsMulti.next(this.myCustomComponents.slice());
// listen for search field value changes
this.myCustomComponentMultiFilterCtrl.valueChanges
.pipe(takeUntil(this._onDestroy))
.subscribe(() => {
this.filterMyCustomComponentsMulti();
});
})
)
.subscribe( (result: any) => {
this.myCustomComponents = result.items;
this.myCustomComponentMultiCtrl.setValue(result.items.find(x => x.id === myCustomComponentId));
});
// resolve("juraj2");
}
}
html часть:
<mat-form-field>
<mat-select name="MyCustomComponentList" [formControl]="MyCustomComponentMultiCtrl" [placeholder]="'MyCustomComponents' | localize" [(ngModel)]="myValue" #multiSelect (selectionChange)="actualChange($event)" required>
<mat-option>
<ngx-mat-select-search [formControl]="MyCustomComponentMultiFilterCtrl" placeholderLabel="search..."></ngx-mat-select-search>
</mat-option>
<mat-option *ngFor="let MyCustomComponent of filteredMyCustomComponentsMulti | async" [value]="MyCustomComponent">
{{MyCustomComponent.MyCustomComponentArabicName}}
</mat-option>
</mat-select>
</mat-form-field>