Can't set property value - html

I'm trying to set initial value of input field using:
<input type="text" id="inputText2" name="inputText2" ngModel #inputText2="ngModel" size="5" autocomplete="off" [value]="'hre'"
autofocus>
Tried everything [value]="example", [ngValue] - here I've got that isn't know property of input field. Thanks for help!

Just let the ngModel handle setting the value for you.
component.html
<input [(ngModel)]="value" />
component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
value = 'hello';
}
Live demo

I'd suggest:
HTML:
<input [(ngModel)]="yourModel" ... />
TS:
...
public class YourComponent{
yourModel: string = '';
...
}
But you can read on other solutions from the official guide here.

Related

Input field of type number is not showing default values (in angular)

I have the following code in stock-status.component.ts file
#Component({
selector: 'app-stock-status',
template:`
<input type="number" value='0' min='0' required [(ngModel)]='updatedStockValue'/>
<button class="btn btn-primary" [style.background]='color' (click)='stockValueChanged()'>Change Stock Value</button>
`,
styleUrls: ['./stock-status.component.css']
})
As you can see in the image it is not showing the default value as 0 enter image description here
And whenever I click the Button when no data is initialized , it shows NaN which is not what I want
Any Kind of Help and Guidance would be appreciated
The ngModel binding might have precedence here. You could ignore the value attribute and set updatedStockValue in it's definition.
Try the following
#Component({
selector: 'app-stock-status',
template:`
<input type="number" min="0" required [(ngModel)]="updatedStockValue"/>
<button class="btn btn-primary" [style.background]="color" (click)="stockValueChanged()">Change Stock Value</button>
`,
styleUrls: ['./stock-status.component.css']
})
export class AppComponent {
updatedStockValue: number = 0;
...
}
You can initialize a variable in the template with ng-init if you don't want to do it in the controller.
<input type="number" min='0' required [(ngModel)]='updatedStockValue'
ng-init="updatedStockValue=0"/>

How can I set input placeholder text in component file in Angular

I'm new to Angular and Typescript. I have the input with a placeholder below, is there a way to change the placeholder text from my component file?
<input id="city" class="form-control" placeholder="City or Town">
You can just bind the placeholder attribute. Stackblitz
<input id="city" class="form-control" [placeholder]="placeholder">
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
placeholder = 'Angular';
}

ngModel in Angular Form

I'm trying to access to data form my form in the TS file.
I got error : RROR TypeError: Cannot read property 'name' of undefined
My code is like this:
import { Component, OnInit } from '#angular/core';
import { employee } from '../models/Employee';
import { NgForm } from '#angular/forms';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#Component({
selector: 'app-employee-form',
templateUrl: './employee-form.component.html',
styleUrls: ['./employee-form.component.css']
})
export class EmployeeFormComponent implements OnInit {\
data: employee;
constructor() { }
ngOnInit() {
}
onSubmit(form:NgForm ) {
alert("Hello " + JSON.stringify(this.data));
}
}
<div class="container">
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<div class="form-group">
<label for="form">name</label>
<input type="text" class="form-control" id="name" [(ngModel)]="data.name" required>
</div>
</div>
<button type="submit" class="btn btn-success" >Submit</button>
</form>
</div>
I didnt find my mistake, any idea?
thanks
Do the template binding with a safe navigation operator. This way, if "data" is not defined, your code will not try to read prop name from it.
<input type="text" class="form-control" id="name" [(ngModel)]="data?.name" required>
In case, if the prop data is undefined and you want to use data as a container to store the form values then you have to at least create an empty object, for example, initialize data as data = {} It will create keys on the fly.
The solution is that you shouldn't make the data null ever.
And initialize the data as
data = {} as employee;

2 text fields mapped to same formcontrolname angular 2+

I have a requirement where in i have 2 search fields one on top and one on bottom. Need to keep both text fields in sync i.e. user can type in top or bottom search text box. If he types in top box it should reflect in bottom box and vice versa. I am using reactive angular forms
HTML Code:-
<form [formGroup]="form">
<div class="form-group">
<label for="searchBox1">Search Box 1</label>
<input type="text" class="form-control" id="searchBox1" name="searchBox1"
formControlName="searchBox" placeholder="Search Box 1" (change)="addText($event.target.value)">
</div>
<div class="form-group">
<label for="searchBox2">Search Box 2</label>
<input type="text" class="form-control" id="searchBox2" name="searchBox2"
formControlName="searchBox" placeholder="Search Box 2" (change)="addText($event.target.value)">
</div>
</form>
component.ts code:-
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
'searchBox': new FormControl(null, Validators.required)
});
}
addText(value) {
this.form.setValue({
'searchBox': value
});
}
}

Can't wrap my head around capturing form data (Angular)

I am simply trying to create a mockup of a login page, and need to get the username and password values entered into the form, and use those values to validate whether the user should be authenticated. I've looked at a dozen tutorials and can't seem to understand it fully. Here is what I have:
login.component.html
<form #f="ngForm" (ngSubmit)="loginUser()">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"
[(ngModel)]="model.username" #username="ngModel"
class="form-control" required>
<label for="password">Password</label>
<input type="password" id="password" name="password"
[(ngModel)]="model.password" #password="ngModel"
class="form-control" required>
<div style="padding-top:20px">
<button type=submit class="button">Login</button>
</div>
</div>
</form>
login.component.ts (I'm going wrong here somewhere, but I tried. The "if" statement is definitely wrong)
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { NgForm, FormControl, FormGroup, ReactiveFormsModule } from '#angular/forms'
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
myForm: FormGroup
constructor(private router: Router) {
}
ngOnInit() {
}
loginUser(f: NgForm) {
if (f.value == "admin" && f.value == "admin"){
this.router.navigate(['mockup']);
}
}
}
There are a few issues:
1- Model is not defined anywhere. Therefore, model.username is not valid. Just make it username or define model somewhere in your calss.
2-You don't need the variables (#username="ngModel") if you are not going to use them in the template. For example, you could do:
<input #myUsernameInput="ngModel">
{{ myUsernameInput.valid }} // true/false
{{ myUsernameInput.value }} the value
and various other checks. But you aren't performing these checks anywhere, so there's no need to have the variables defined.
3- myForm should not be defined in your class, as formGroups are used for reactive forms, not template driven forms. If you want to pass the values to the method, an easy way is like this:
<form (submit)="loginUser(username, password)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"
[(ngModel)]="username" class="form-control" required>
<label for="password">Password</label>
<input type="password" id="password" name="password"
[(ngModel)]="password" class="form-control" required>
<div style="padding-top:20px">
<button type=submit class="button">Login</button>
</div>
</div>
</form>
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { NgForm, FormControl, FormGroup, ReactiveFormsModule } from '#angular/forms'
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
loginUser(username: string, password: string) {
if (username === "admin" && password === "admin"){
this.router.navigate(['mockup']);
}
}
}
The easiest way to to explain template driven forms means that all the work (meaning the building of the form, the validation, etc.) takes place in the template (the html). This is limited because you can't do everything that you could with reactive driven forms. However, reactive driven forms are a bit more complex. Which to choose depends on the situation and the preference, but in this scenario, template driven forms are perfectly valid to use. I'd recommend reading this guide, it's super helpful. https://angular.io/guide/forms