Schalte FormControl in View mit Formbuilder TypeScript unter Verwendung von Angular 8
Wie entferne ich Elemente aus einer HTML-DOM-Ansicht mit NgIf mithilfe von Typescript, nicht HTML? Ich suche nach einer ähnlichen Syntax.
Es ist besser, ein Array in TypeScript zu durchlaufen und Elemente aus der Ansicht zu entfernen, anstatt alle 20 FormControls mit NgIf zu umschließen, das wirkt irgendwie repetitiv.
Derzeit wird Formbuilder und nicht FormArray verwendet. Dieser Link setzt den Stil auf display none, was nach dem, was ich gelesen habe, keine ideale Praxis in Angular ist. Stimmt das?
Angular 2 -> wie man Steuerelemente mit FormGroup ausblendet
Wir haben ein Ausschluss-Array und ziehen es vor, es mit foreach in TypeScript zu deaktivieren
Vielleicht so etwas?
Dies deaktiviert nur das Feld, wird aber weiterhin in der HTML-Ansicht angezeigt
Object.keys(this.customerForm.controls).forEach(key => {
if (this.excludeFormControlArray.indexOf(key) >= 0) {
this.customerForm.get(key).disable; // This only disables the field, still shows in html View
this.customerForm = this.formBuilder.group({
'firstName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'phoneNumber': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'streetName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'emailAddress': [null, [Validators.maxLength(50), Validators.email]],
'city': [null, [Validators.required, Validators.maxLength(200)]],
'state': [null, [Validators.maxLength(200)]],
'zip':[null,[Validators.maxLength(200)]]
});
HTML
//Versuche, das Umbruchsverhalten mit ngIf zu vermeiden, werden die Elemente an einem speziellen Ort auf der Seite platziert, gemäß den UX-Wireframe-Spezifikationen, NgFor war nicht vollständig möglich, die HTML/CSS-Ansicht ist viel komplizierter als dies,
<div class = "row">
<app-input-textbox formControlName = "firstName"></app-input-textbox>
<div class = "row">
<div class = "column">
<app-input-textbox formControlName = "emailAddress"></app-input-textbox>
</div>
<div class = "test">
<app-input-textbox formControlName = "state"></app-input-textbox>
<app-input-textbox formControlName = "zip"></app-input-textbox>
</div>
Antwort #1
Ich sehe, dass Sie ein "app-input" erstellen möchten. Mein Vorschlag ist, dass das app-input den FormGroupDirective-Konstruktor injiziert und direkt [formControl] verwendet, siehe Stackblitz.
@Component({
selector: 'app-input',
template: `
<ng-container *ngIf="control && control.enabled">
{{label}}
<input [formControl]="control">
</ng-container>
`
})
export class HelloComponent {
constructor( @Optional() @Host() private form:FormGroupDirective){}
control:FormControl
@Input() set name(value)
{
this.control=this.form?this.form.form.get(value) as FormControl:null
}
@Input() label: string;
}
Dies ermöglicht uns, eine Form wie zu haben
<form [formGroup]="formGroup">
<app-input name="one" label="One"></app-input>
<app-input name="two" label="Two"></app-input>
</form>
Wenn wir Fehler hinzufügen wollen, können wir die App-Eingabe verbessern, eine Eingabe und eine Funktion verwenden, um den ersten Fehler unter den Fehlern zu bekommen
@Input() errors:any={} //see that, by defect it's an empty object
getError()
{
for (let key of Object.keys(this.errors))
{
if (this.control.hasError(key))
return this.errors[key]
}
}
Und füge der Vorlage etwas wie hinzu
<div *ngIf="control.touched">
{{getError()}}
</div>
Unsere Haupt-App wird wie zum Beispiel
<form [formGroup]="formGroup">
<app-input name="one" label="One" [errors]="{required:'One is required'}"></app-input>
<app-input name="two" label="Two"></app-input>
</form>
Nun, dies ist nur ein Beispiel, ich hoffe, das hilft dir
Antwort #2
Ich habe ein Stackblitz für dich erstellt.
Hier verwende ich ein benutzerdefiniertes Modell (Array), um Felder darzustellen:
<h1>My dynamic form</h1>
<form [formGroup]="formGroup">
<div *ngFor="let input of inputList">
<label>{{ input.label }}</label>
<input type="{{ input.type }}" formControlName="{{ input.formControlName }}">
<span (click)="removeInputField(input)">Remove</span>
</div>
<div>
<button type="button" (click)="addInputField()">Add Input Field</button>
<button type="submit">Submit</button>
</div>
</form>
Und hier sind zwei Methoden, um Steuerelemente hinzuzufügen und zu entfernen:
addInputField() {
const formControlName = prompt("FormControlName input: ");
const inputType = prompt("Type input: ");
const label = prompt("Label input: ");
const inputData = {
inputType: inputType,
formControlName: formControlName,
label: label
};
this.inputList.push(inputData);
this.formGroup.addControl(
inputData.formControlName,
this.formBuilder.control("")
);
}
removeInputField(inputField: InputField) {
this.formGroup.removeControl(inputField.formControlName);
this.inputList = this.inputList.filter(field => field !== inputField);
}
Der Hauptschritt besteht darin, die Methoden removeControl und addControl aufzurufen.
In Ihrem Fall sollten Sie einfach this.customerForm.removeControl(key) aufrufen.
