angular : passing the input value to the component - html

I want to affect the value of this input to a variable 'numToAdd' which is in my component and then add 1 to the variable 'numToAdd', but I can't pass the value of the html input to my component variable 'numToAdd'. How to bind my html input to a variable in the component ?
my html code
<input type="number" id=num class=num>
my component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-afficher-projets',
templateUrl: './afficher-projets.component.html',
styleUrls: ['./afficher-projets.component.css']
})
export class AfficherProjetsComponent implements OnInit {
ngOnInit(): void {}
numToAdd: number;
constructor() { }
add: void {
this.numToAdd++;
}
}

Two-way binding a primary functionality of angular. Use the ngModel directive to bind input to variables.
<input type="number" id="num" class="num" [(ngModel)]="numToAdd">
The above code binds the variable numToAdd with the input. Find more details here

Related

What is the purpose of <app-control-message> in angular 8 and how it is used?

I need to create a button for uploading a file in my form. I am using tag in my html but it is throwing an error : Can't bind to 'control' since it isn't a known property of 'app-contorl-message'.
Here is my html code -
<div class="col-lg-6">
<div class="form-group">
<div class="custom-file">
<input *ngIf="mode == 'CREATE'" type="file" (change)="onFileSelect($event)"
accept=".jpg,.jpeg,.png"/>
<app-contorl-message [control]="form.get('file')"></app-contorl-message>
</div>
</div>
</div>
here is def of onSelect($event) :
onFileSelect(event) {
this.form.get('file').setValue(event.srcElement.files);
this.fileData = event.srcElement.files;
console.log(event);
}
Thanks in advnace!
In your AppControlMessageComponent you need to create an #Input() named control. To learn more about inputs and output, visit: https://angular.io/guide/inputs-outputs
app-control-message.component.ts
import { Component, OnInit, Input } from "#angular/core";
#Component({
selector: "app-app-control-message",
templateUrl: "./app-control-message.component.html",
styleUrls: ["./app-control-message.component.css"]
})
export class AppControlMessageComponent implements OnInit {
#Input() control; // Input whose value parent component will provide
constructor() {}
ngOnInit() {}
}

Angular 2+: Input decorator not reflecting checkbox

I have a component
timeBoxSelector
HTML:
<input type="checkbox" [(ngModel)]="selected">
TS:
#Component({
...
})
export class TimeboxComponent implements OnInit {
#Input() selected: boolean;
constructor() {}
ngOnInit() {
console.log('Selected: ', this.selected);
}
}
Now, when I create
<app-timebox selected="false"><app-timebox/>
<app-timebox selected="true"><app-timebox/>
In both cases, the checkbox initially appears as selected. Why is this the case, and how can I fix it?
In both cases, you are binding non empty strings, which are truthy values. Use the brackets notation to tell Angular that the bound value is to be evaluated as a Javascript expression:
<app-timebox [selected]="false"><app-timebox/>
<app-timebox [selected]="true"><app-timebox/>

Angular2 dynamically generating Reactive forms

I have a concept question and would like some advice.
So I have a component, myFormArray, which is a reactive form. It takes in an input array, and creates a number of FormControls accordingly.
#Component({
selector: 'myFormArray',
templateUrl: 'formarray.component.html'
})
export class FormArrayComponent{
#Input() classFields: any[];
userForm = new FormGroup();
ngOnInit(){
// psuedocode here, but I know how to implement
for (# of entries in classFields)
userForm.FormArray.push(new FormControl());
}
Now, in my parent html, I will be dynamically generating multiple myFormArrays. If that is confusing, assume I'm doing this:
<myFormArray [classFields] = "element.subArray"/>
<myFormArray [classFields] = "element2.subArray"/>
<button (click) = "save()"> //I don't know how to implement this!
And at the very end of the page, I want a save button, that can somehow grab all the values the user inputs in to all the forms, and pushes all this data to an array in a Service component. I'm not sure exactly how to do this part. Note that I don't want individual submit buttons for each dynamically generated form component.
How would I implement this functionality? Thanks!
Your start is good, but you have to write your source code differently.
Instead of this example app.components.ts is main component and my-array.component.ts is child component.
Our test data
classFields1: any[] = ['firstname', 'lastname', 'email', 'password'];
classFields2: any[] = ['country', 'city', 'street', 'zipcode'];
Step 1. Use FormBuilder for form creation (app.component.ts)
You must import FormBuilder and FormGroup from #angular/forms like this:
import { FormBuilder, FormGroup } from '#angular/forms';
and then define in constructor:
constructor(private formBuilder: FormBuilder) { }
Step 2. Define new empty FormGrooup
Now you can define new empty FormGroup in ngOnInit like this:
ngOnInit() {
this.myForm = this.formBuilder.group({});
}
Step 3. Create FormControls dynamically (app.component.ts)
Now you can start with dynamically creation of your FormControls by iteration of classFields. For this I would recommend to create own function. This function gets two parameter: arrayName and classFields. With arrayName we can set custom name of our FormArray-control. classFields-Array we will use for iteration. We create constant variable for empty FormArray, which we called arrayControls. After this we iterate over classFields and create for each element FormControl, which we called control, and push this control into arrayControls. At the end of this function we add our arrayControls to our Form with custom name by using arrayName. Here is an example:
createDynamicArrayControls(arrayName: string, classFields: any[]) {
const defaultValue = null;
const arrayControls: FormArray = this.formBuilder.array([]);
classFields.forEach(classField => {
const control = this.formBuilder.control(defaultValue, Validators.required);
arrayControls.push(control);
})
this.myForm.addControl(arrayName, arrayControls);
}
Import FormControl and FormArray from #angular/forms. Your import line should be like this:
import { FormBuilder, FormGroup, FormArray, FormControl } from '#angular/forms';
Now call createDynamicFormControls-Function in ngOnInit.
Step 4. HTML Template for this dynamic Form (app.component.html)
For this example I create following template:
<h1>My Form</h1>
<form [formGroup]="myForm">
<div formGroupName="test1">
<app-my-array [classFields]="classFields1" [arrayFormName]="myForm.controls.test1"></app-my-array>
</div>
<div formGroupName="test2">
<app-my-array [classFields]="classFields2" [arrayFormName]="myForm.controls.test2"></app-my-array>
</div>
<button type="button" (click)="saveForm()">Submit</button>
</form>
Here we have new div element with formGroupName. This group name is our arrayName in our form. We give our form arrays via #Input to my-array.component.
Step 5. MyArrayComponent
Now this component is very simnple:
import { Component, OnInit, Input } from '#angular/core';
import { FormGroup } from '#angular/forms';
#Component({
selector: 'app-my-array',
templateUrl: './my-array.component.html',
styleUrls: ['./my-array.component.css']
})
export class MyArrayComponent implements OnInit {
#Input() classFields: any[];
#Input() arrayFormName: FormGroup;
constructor() { }
ngOnInit() { }
}
Here we have only two #Input varibales. (I know, this variable can have a better names :-) ).
Step 6. HTML for MyArrayComponent
<div [formGroup]="arrayFormName">
<div *ngFor="let class of arrayFormName.controls; let index = index;">
<label [for]="classFields[index]">{{ classFields[index] }}</label>
<input type="text" [id]="classFields[index]" [formControlName]="index" />
</div>
</div>
<br>
And here is working example on Stackblitz: https://stackblitz.com/edit/angular-wawsja
If you have some question ask me in comments or read the Angular documentation abour Reactive Forms here.

very basic angular2 form not getting validated

I have a very basic form consisting of a input field and a button. I am trying to use angular2 validators to show an error message when anything other than numbers are entered into the input field and also to disable the submit button when the input field is invalid or empty. For some reason the error message shows regardless of what gets entered... Any idea what i'm doing wrong?
my code:
app.component.html:
<div class="row">
<div class="col-md-4 col-md-push-4">
<form [formGroup]="barcodeForm" role="form" (ngSubmit)="submitBarcode(barcode)" >
<div class="form-group">
<input type="number" class="form-control" id="barcode" placeholder="Enter Barcode" [formControl]="barcodeForm.controls['barcode']" [(ngModel)]="barcode" name="barcode" #focusInput>
<div [hidden]="barcode.valid || barcode.pristine" class="alert alert-danger">A barcode can only consist of numbers (0-9)...</div>
</div>
<button class="btn btn-submit btn-block" [disabled]="!(barcode.valid) || barcode.pristine">Submit</button>
</form>
</div>
</div>
part of app.component.ts:
import { Component, ViewChild, ElementRef, AfterViewInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { RestService } from "./services/rest.service";
import { ProductModel } from "./models/product.model";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
#ViewChild('focusInput') focusInput: ElementRef;
barcode: string;
barcodeForm: FormGroup;
product: ProductModel;
constructor(fb: FormBuilder, private restService: RestService){
this.barcodeForm = fb.group({
'barcode':['', [Validators.required, Validators.pattern("[0-9]+")]]
});
}
In angular2 there are two types of forms: template driven and model driven.
Model driven is defining the form's structure in code and binding inputs to its controls (via formControl and formGroup).
And template driven is using ngModel and defining validators on the template.
I can see most of your code is targeted for model driven which in my opinion is better anyway, but you still have ngModel on your input, do you need it for something?
I dont see you using it anywhere other than barcode.valid which shouldn't work since barcode is merely a string. You want to bind the disabled property to barcodeForms.controls['barcode'].valid instead and then remove the use of ngModel. It might conflict with formControl since both of them initialize a FormControl instance for that element.

Binding a value from custom control to html control using angular 2 directives in typescript

I have created a custom control directive as "my-text-box", inside this directive I am using html control <input>, I need to pass values from my custom control to html input control. In angular1 simply I am using like <my-text-box id="1" name="Box 1"> using my custom attributes of scope variables in directive, i assigned the values to html control like <input type="text" id="{{id}}" name={{name}} > how can i use this scenario in angular 2.
Here is my sample code:
AppComponent.ts
import {Component} from '#angular/core';
import {TextBoxComponent} from './TextBoxComponentDirective';
#Component({
selector: 'my-app',
template: '<h1>{{title}}</h1> <my-text-box id="66" name="MyText1"></my-text-box>',
directives:[TextBoxComponent]
})
export class AppComponent {
title="Sample TextBox";
}
TextBoxComponentDirective.ts
import {Component,Input,Directive} from '#angular/core';
#Component({
selector:'my-text-box',
templateUrl: './TextBoxTemplate.html',
})
export class TextBoxComponent {
#Input() id;
}
TextBoxTemplate.html
<input type="text" [name]="name" [id]="id"/>
You can use #Input() for this:
#Component({
selector: 'my-text-box',
template: `
<input type="text" [id]="id" [name]="name" >
`
})
export class MyTextBoxComponent {
#Input() id;
#Input() name;
}
In your parent component you now can use it like so:
<my-text-box id="1" name="Box 1">
Or if you need to bind to variables:
<my-text-box [id]="someId" [name]="theBoxName">
Working Plunker for example usage