How to set dropdown value in angular 7 - angular6

I am trying to set dropdown value by programmatically using formcontrolname but not working.I have given my code below.How to set dropdown value that?Anyone can have idea?please help to find the solution.
app.component.html:
<p-dropdown [values]="dropdownData" fornControlName="datavalue"><p-dropdown>
app.component.ts:
dropdownData=[
{name:'UK',value:'UK'},
{name:'USA',value:'USA'},
{name:'CHINAA',value:'CHINAA'}
];
this.myform=this.fb.group({
datavalue:[null]
});
ngOnInit(){
this.myform.controls['datavalue'].setValue("USA");
}

This could work if you changed setValue as follows.
this.myform.controls['datavalue'].setValue(dropdownData[0]);
You should however inverse the logic and address the model from within your template using ngModel.
app.component.html:
<p-dropdown [values]="dropdownData" [(ngModel)]="selectedData"><p-dropdown>
app.component.ts:
dropdownData = [
{name:'UK',value:'UK'},
{name:'USA',value:'USA'},
{name:'CHINAA',value:'CHINAA'}
];
selectedData = dropdownData[0];

Please set the value like below in your app.component.ts:
this.myform.controls['datavalue'].setValue("USA", { onlySelf: true });
Also, please change the code in app.component.html like below:-
<p-dropdown [options]="dropdownData" fornControlName="datavalue"><p-dropdown>
Hope this helps you.

Related

Angular does not update value to View when change in ngAfterViewInit

I have this in view
<span [ngStyle]="{width: optionActiveWindowSize}" class="option-active-window"></span>
<ng-container *ngFor="let op of options; let i = index">
<div [ngClass]="{active: i === activeIndex"}></div>
</ng-container>
Ts Code
ngAfterViewInit(): void {
const activeOption =
this.horizontalOptionRef.nativeElement.getElementsByClassName('active');
this.optionActiveWindowSize = activeOption[0].offsetWidth + 'px';
}
Value of optionActiveWindowSize does not change in the DOM after it was changed in afterViewInit.
Can you please tell me why and how to fix it?
There could be couple of problems.
Make sure, optionActiveWindowSize has a string value with px defined in the end like,
eg. optionActiveWindowSize = '20px'. Then,
[ngStyle]="{width: optionActiveWindowSize}"
should work.
I assume, optionActiveWindowSize has a numeric value like optionActiveWindowSize = 20, then you should change it as,
[ngStyle]="{ 'width.px': optionActiveWindowSize}"
OR
[style.width.px]="optionActiveWindowSize"
Hope, this will help !
NOTE: Forgot to mention as #M Fuat NUROGLU mentioned, span doesn't have width prop. So, you may want to change it to div.
You are binding styles after those styles are already rendered.
no event loop there to track it.
see detailed info from here : https://angular.io/api/core/AfterViewInit
If you want to imply those styles before your page is rendered.
use this :
const activeOption =
this.horizontalOptionRef.nativeElement.getElementsByClassName('active');
this.optionActiveWindowSize = activeOption[0].offsetWidth + 'px';
In your
ngOnInit()
method.
I found the reason. It's because changeDetection is ChangeDetectionStrategy.OnPush.
changeDetection: ChangeDetectionStrategy.OnPush

Hide and show div in Angular

I want to show a div that is hidden when I click on a Button. I am working with Angular7 I tried some methods but they didn't work. Please help me. Thanks
You can use *ngIf
Template:
<div *ngIf="display">Test Data</div>
<input type="button" value="click" (click)="update"/>
Component:
display = true;
update(){
this.display = !this.display;
}
You can link an *ngIf directive to your component with a variable set to True,
then on the button click modify the variable to false.
Template:
<div *ngIf='variable'></div>
<button (click)='showContent()'></button>
Component:
variable = true;
showContent() {
this.variable = false;
}
change display or visibility depending on what you need.
use ngStyle or ngClass to set it based on a condition

How to set formgroup data from angular

I have a formgroup like below:
this.myform = this.fb.group({
mydata: ''
});
I was able to set the data with formgroup setValue but in rendering the values in HTML, the option was not selected.
This is the HTML:
<div *ngFor="let item of (items$ | async); index as i; first as first">
<input type="radio" id="{{item.itemId}}" name="test" value="{{item.itemId}}" [formControl]="myform.controls.mydata"
selected = "(items$ | async).length ===1">
</div>
This doesnot select the first input label in HTML but in typescript the form is valid .
Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control.
this.myform.setValue({ mydata: 'yourData' });
use the patchValue to set the value for the whole form
this.myform .patchValue({ mydata: 'yourData' });

How can I change component without changing URL in Angular?

I would like to change component without changing URL. Let's assume that I have a component register. When I open my website I have url www.myweb.com. Then I would like to register by clicking sign up. I would like to display my component register without changing URL. Should I use ngIf or something else? Can you show me example how it should be done?
UPDATE I am sorry, but it seems to me that I was misunderstood. I tried
this solution:
login.component.ts:
showSignUp: boolean = false;
login.component.html:
<button (click)="showSignUp = true">Sign Up</button>
<register *ngIf="showSignUp"></register>
However when I clicking the button Log in I get this:
before:
after clicking:
After clicking the button Log in I would like to get a new website but with the same URL like this:
UPDATE
What do you think about solution shown below? In html file I will be checking whether variable authenticated is equal true. If so then I will display home component.
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.authenticated = true;
// this.router.navigate([this.returnUrl]);
},
error => {
this.authenticated = false;
this.alertService.error(error);
this.loading = false;
});
}
UPDATE
Unfortunately it doesn't work. Any ideas how can I use it with this button?
<button [disabled]="loading" class="btn btn-primary">Log in</button>
You can use *ngIf and show the component in condition!
examle
In your sign up component, set a variable and change its value on click of sign up button. And display your register component on click of the login by pitting the condition in display
// sign up component
showRegister = false;
in your sign up component html
<register *ngIf="showRegister"></register>
Yes, this is a perfect use case for ngIf. Try not to over engineer it.
ngIf is the way to go on this kind of thing.
Just put in your component code something like
showSignUp: boolean = false;
then in template:
<button (click)="showSignUp = true">Sign Up</button>
<register *ngIf="showSignUp"></register>
And since you seem new to Angular, I'll mention that in order to use ngIf in template, your module needs to import the CommonModule like
import { CommonModule } from '#angular/common';
imports: [
CommonModule,
]

Accessing Object properties, from HTML Select.

Scenario:
I am trying to access a property (code) of a ng-Model object (myRide).
I've tried doing this by
<select ng-model = "myRide"
ng-change = "getCode(myRide.code)">
...and at getCode,
alert(parameter) //which should be myRide.code.
I've also tried to do this by
<select ng-model = "myRide"
ng-change = getCode(myRide)
(Note: 'myRide' is passed, not 'myRide.code') ...and at getCode,
alert(myRide.code).
myRide does indeed contain a property called 'code', which is not undefined.
Problem: Both tries do not produce the wanted outcome.
How can I make it display the property (code)?
Here is the JSFiddle: http://jsfiddle.net/a2J6z/1/
The better way to do this is to restructure the view. Instead of using ng-repeat on options inside of a select, use the ng-options directive. Then, you can bind the actual object to the model instead of just a JSON string, which is what your current fiddle is doing.
Your new select looks like
<select ng-options="car.Name for car in myGarage" ng-model="myRide" ng-change="getCode(myRide)">
</select>
Then in your controller
$scope.getCode = function(car){
alert(car.code);
}
An updated fiddle:
http://jsfiddle.net/a2J6z/5/
I updated the fiddle:
http://jsfiddle.net/a2J6z/3/
var ngApp = angular.module('ngAppl',[]);
function aControlla($scope){
$scope.myRide = "bus";
$scope.getCode = function(car){
alert(JSON.parse(car).code);
}
$scope.myGarage = [
{Name: "Toyota 86", code:"1"},
{Name: "Hyundai Genesis Coupe", code:"2"},
{Name: "Nissan GTR", code:"3"},
{Name: "Veyron", code:"4"}
];
};
And
<div ng-app="ngAppl">
<div ng-controller="aControlla">
<select ng-model="myRide" ng-change="getCode(myRide)">
<option ng-repeat="car in myGarage">{{car}}</option>
<!--Note: value of myRide MUST be simply 'car' (not say, 'car.Code')-->
</select>
<br/> This shows that 'myRide' contains the property called 'Name', and importantly, 'code':<br/> {{myRide}}
</div>
</div>
Basically I just had it alert what car was with myRide as the parameter, it showed the JSON string so I added the parse to get it to give me the code. There may be a better way I'm an AngularJS noob so to speak.