Reputation: 866
I currently have an Angular form that returns the form values using (ngSubmit). I want to add another property to, lets say an input, where I can specify a search operator like (contains, equal, starts with, etc).
How can I get the operator with the values from the form?
Here's an example. I added operator
to both inputs. I'd like to return this in the form value when search is called. Is there a custom directive I could write or a way to extend form values?
<form #searchForm="ngForm" (ngSubmit)="search(searchForm)">
<input type="text" name="name" [(ngModel)]="name" operator="contains" />
<input type="text" name="email" [(ngModel)]="email" operator="equal" />
</form>
search(form: NgForm) {
console.log(form.value);
}
So I would get something like this back or be able to bind to that operator.
name: { value: 'John', operator: 'contains' }
Upvotes: 0
Views: 1523
Reputation: 692121
Just use the appropriate model. The operator doesn't need to be in the view:
this.model = {
name: {
value: '',
operator: 'contains'
},
email: {
value: '',
operator: 'equal'
}
};
search() {
console.log(this.model);
}
and in the view:
<form (ngSubmit)="search()">
<input type="text" name="name" [(ngModel)]="model.name.value" />
<input type="text" name="email" [(ngModel)]="model.email.value" />
</form>
Upvotes: 1
Reputation: 4918
You can use native javascript to achieve this:
search(form: NgForm) {
console.log(form.value);
const element: HTMLElement = document.getElementById('my-input');
console.log(element.getAttribute('operator'));
}
and:
<form #searchForm="ngForm" (ngSubmit)="search(searchForm)">
<input type="text" id="my-input" name="name" [(ngModel)]="name" operator="contains" />
<input type="text" name="email" [(ngModel)]="email" operator="equal" />
<button type="submit">Submit</button>
</form>
You can't have it be a part of the form itself though, unless you add another input below it, like a radio button or something. To me, that makes more sense than how I did it above.
Upvotes: 0