Creating Input element and appending it to form with ngModel - html

I have a select dropdown with its onChange event mapped to a function which should create an input element with ngModel along with other attributes, and append it to another element, like so:
<select class="form-control" id="addUsers" (change)='addProfession($event.target.value)'>
<option *ngFor='let profession of professions' [value]='profession.ProfessionTypeName'>
{{ profession.ProfessionTypeName }}
</option>
<div #addUsersProfessionsSelect></div>
Below you can finds the function bound to the select's change event:
addProfession(professionName: string) {
let profession = new Profession(Profession.nameToIdMap[professionName], professionName);
this.shouldDisplayProfessionsInputs = true;
let professionInput = `<div>${profession.professionName}
<input type="text" class="form-control" [id]='${profession.professionName}' name='${profession.professionName}'
[(ngModel)]="newCampaign.users[${profession.professionTypeId}]"></div>`
let safeHTML = this.sanitizer.bypassSecurityTrustHtml(professionInput);
let element = this.renderer.createElement(this.addUsersProfessionsSelect.nativeElement, 'div');
this.renderer.setElementProperty(element, 'outerHTML', safeHTML);
}
addProfession does create and append the element, but it ignores all attributes. Here's the added input element:
<input type="text" class="form-control" [id]="Stylist" placeholder="Stylist"
name="Stylist" [(ngmodel)]="newCampaign.users[6]">
Do note the lowercase attribute names, and ignored brackets on the [id] attribute.
I'd love any help on this subject. Thanks!

Instead of directly manipulating the DOM, I pushed the new profession to an array on which I used an *ngFor and bound the data I needed to the iterator.

Related

How do I reset select and ng-select to first option dynamically

UPDATE ::
https://stackblitz.com/edit/angular-ivy-tggo2e?file=src%2Fapp%2Fapp.component.ts
This stack is basically a TLDR of this post.
UPDATE 2::
Ok basically in that blitz, example 2 works. haha. in my code I was resetting that arr2 in my subscribe after the API call but doing it before the API call fixed it. Now I just have to figure out how to give it that first option (Pick something..) on initial load instead of a blank box.
///////////////////
So basically I have a cascade of select dropdowns. Lets call them form1, form2, form3.
When I select form1, it will call an API using that selection and dynamically give me an array to use for form2 options. same for form3,4,5,etc.
Now this is no problem up to here. But when I have selected form1,2,3 and then I select form1 again, I want form 2 and 3 to reset to my disabled option 1 but I can't seem to be able to get that to happen.
Component.ts
dropdownForm() {
this.dropdownForm = new FormGroup({
form1: new FormControl(),
form2: new FormControl(),
form3: new FormControl(),
form4: new FormControl()
)}
callAPI(query) {
// API CALL
}
changeONE(e) {
// this.arr2 = [];
// reset this.dropdownForm.form2 back to the first option 1('Pick something..) to be 'selected' and 'disabled'
// this.callAPI(e)
}
changeTWO(e) {
// this.arr3 = []
// reset this.dropdownForm.form3
this.callAPI(e)
}
changeTHREE(e) {
// this.arr4 = []
// reset this.dropdownForm.form4 -- this one is ng-select so it is way different than the others.
// this.callAPI(e)
}
HTML
<form [formGroup]="dropdownForm">
<div>
<div>
<label for="form1">Form1</label>
<select id="form1"
(change)="changeONE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr">{{item}}</option>
</select>
</div>
<div>
<label for="form2">Form2</label>
<select id="form2"
(change)="changeTWO($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr2">{{item}}</option>
</select>
</div>
<div>
<label for="form3">Form3</label>
<select id="form3"
(change)="changeTHREE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr3">{{item}}</option>
</select>
</div>
<div>
<label for="form4">Form4:</label>
<ng-select [multiple]="true" placeholder="Pick something" (change)="changeFOUR($event)" >
<ng-option *ngFor="let item of arr4">{{item}}</ng-option>
</ng-select>
</div>
I've tried adding formControlname in my selects but that makes the select act weird for some reason... maybe its because my 'new FormControl('')' is wrong? But it makes my form1,2,3 just preselect something random in my optionsArr.
And even then, if i do this.dropdownForm.controls.form1.reset() or something like that, it doesn't do anything. it will just reset the value instead of the resetting the dropdown box(which I'm not even using anyways.. haha. I should be but I'm using using that changeONE() and $event to get the value)
Thank you
EDIT::
I just tried
component.ts
this.dropdownForm.get('form2').reset()
HTML
<select id="form1"
(change)="changeONE($event)" formControlName='form1'>
And basically when I have form1 and form2 selected and I go back and select form1 with that this.dropdownForm.get('form2').reset(), it won't reset form2. Instead, it will select the first item in the new updated arr2 (after i get arr2 from that API call) on the second option of that select instead of going to that disabled option one.

Add a checked attribute to a dynamic radio button

I'm building a *ngFor dynamic radio button. I need to add some kind of attribute that can be used to determine if the button is active or not. This is not for the purpose of functionality, the selection builds the property on my reactive form fine. The purpose is to satisfy testing.
<label *ngFor="let order of orders">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
I've tried adding a checked attribute but this just adds the attribute to all radios. I thought angular provided a ngChecked property, but I think that was for AngularJS.
Any solution to determine/show that the selected radio is active would be a solution.
https://stackblitz.com/edit/angular-t2gd4g
simply by get the value of the form control orders you will be applied to know the selected one or in case of apply a spesifect design you can add a checked class for the selected one
<label *ngFor="let order of orders"
[ngClass]="{'checked':form.get('orders').value == order.id}">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" />
{{order.name}}
</label>
another way to get the selected order by create a property
get selectedOrder() {
const selected =this.form.get('orders').value;
if (selected) {
return this.orders.find(o => o.id == selected )
} else {
return null
}
}
demo 🚀
In your .ts file declare changeHandler() function like this :
changeHandler(index){
console.log(`radio-button ${index+1} is active`);
}
In your .html file, in your *ngFor declare index which can be used to find the current state of checkbox. So the following demo shows which checkbox is active :
<label *ngFor="let order of orders; let i = index;">
<input formControlName="orders" type="radio" name="orders" [value]="order.id" (ngModelChange)="changeHandler(i)"/>
{{order.name}}
</label>
Demo : enter link description here
Note : see console to see active button

reset() method for resetting form fields results in errors

I am using ngForm in html and in typescript implemented resetting form fields in OnCickSubmit(). It performs as expected and thus does clear the form's select field but resetting also seems to show 400 bad errors for api calls behind populating the form fields.Eg:dataChanged() is actually calling api in back-end to populate the field and after successful submit then reset happens which clears field but why is the function called again and indeed api called again. Is there a way to avoid this?
html :
<form id = "myForm" #myForm = "ngForm" (ngSubmit) = "onClickSubmit(myForm.value)">
<label>Name</label>
<select ngModel name= "cname" (ngModelChange)="dataChanged($event)" required>
<option [ngValue]="data.name" *ngFor = "let data of result">{{data.name}}</option>
</select><br/>
<input class = "button" align = "center" type = "submit" value = "Apply" [disabled]="!myForm.valid"><br/>
</form>
In typescript onClickSubmit():
anotherfunc();
var resetForm = <HTMLFormElement>document.getElementById("myForm");
resetForm.reset();
If I able to understand your problem properly, don't use getElementById to form reset in angular. we can do form reset in other ways and they are lot simpler than this.
do some changes in your component and template like below
yourComponent.html
<form id = "myForm" #myForm = "ngForm" (ngSubmit) = "onClickSubmit(myForm.value)">
<label>Name</label>
<select [(ngModel)]="dataName" name= "cname" (ngModelChange)="dataChanged($event)" required>
<option [ngValue]="data.name" *ngFor = "let data of result">{{data.name}}</option>
</select><br/>
<button class = "button" align = "center" type = "submit" value = "Apply" [disabled]="!myForm.valid">submit</button><br/>
</form>
yourComponent.ts
dataName: string;
onClickSubmit(event: any){
// this.service.sendPost(){ <= call your method here
on successful response clear the form
if(data.status == 200)
this.dataName = undefined;
//}
}
your using input for submitting the form, it's recommended to use button for that. I changed it in html

Hide 'Zero' value in input using typescript and Angular 2

<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel">
Here I have to hide zero amount while user entering the values.
If he enters all zero's then only we have to hide not in cases like 20,30,100 etc...
I'm using Angular 2.
<input type="text" class="form-control"
id="transactionAmount"
maxlength="10"
OnlyNumber="true"
[(ngModel)]="userBalance.transactionAmount"
name="transactionAmount"
placeholder="Amount"
required
#transactionAmount="ngModel"
(keyup)="hideZero()>
Added This keyUp event in Html and in .ts added below code
hideZero(){
if(this.userBalance.transactionAmount === '0' ){
this.userBalance.transactionAmount = '';
}
}
Working Absolutely fine
/* In your ts */
validateNumber(value: String) {
userBalance.transactionAmount = value && value.replace(/(?:0*)(\d*)/g, (_,value1) => {
return value1;
})
}
<input (input)="validateNumber($event)">
Try using (ngModelChange) event which will trigger when user types values. By using regex, you can remove the last zero value and update the DOM. Hope this helps.
Angular 0 value don't display
<span *ngIf="!pro.model === '0'">{{ pro.model }}</span>
Like this,
When model value is zero that time don't display model value.
If model value is not zero that time show model value in your html pages.

how populate a input hidden with vuejs 2?

i want to know how pass the value that return this function to the input hidden i try with the directive v-input but doesn't work, how can i found the solution to this?.
here is the computed function:
computed:{
currentDate: function (){
this.date = moment().format("D-MM-YYYY");
return this.date;
}
thats the view:
<input type="hidden" name="customfield" class="form-control" v-model="fillProfile.customfield">
If you expect currentDate to be the value of your hidden field, you should bind it like so:
<input type="hidden" name="customfield" class="form-control" :value="currentDate">
v-model is a two-way binding, and hidden inputs are not interactive, so there is no point in using it.