I’m trying to change the dirty
flag of a form
using JavaScript through its DOM element.
To achieve this, I’m utilizing @ViewChild
to access the element and then reading it in the ngOnInit
lifecycle method (it can be done in different ways, but the goal in this step is to get the native element).
Once I have the form’s DOM element, I attempt to dispatch an event to the form to change/trigger the dirty
flag.
However, this approach isn’t working.
Does anyone have suggestions on how to accomplish this?
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<h1>Welcome from {{ name }}!</h1>
<a target="_blank" href="https://angular.io/start">
Discover more about Angular
</a>
<form #ngForm="ngForm" name="ngform">
<input [(ngModel)]="foo" name="foo">
</form>
Is it dirty? {{ngForm.dirty | json}}
`,
})
export class App {
name = 'Angular';
@ViewChild('ngForm', { static: true, read: ElementRef }) form!: ElementRef;
foo = '';
ngOnInit() {
const el = this.form.nativeElement;
el.dispatchEvent(new Event('change'));
console.log({ el });
}
}
2
Answers
You can read the
NgForm
instead of theElementRef
and use themarkAsDirty
method:Try this one
Dispatch a
change
event to the form element.Call the
markAsDirty()
method on the form.This will dispatch a
change
event to the form element, which will trigger themarkAsDirty()
method to be called. This will mark the form as dirty.