#Input not Binding data from component - angular2-forms

Angular2 #Input component is not Binding data from another component
DummyComponent.ts
import { Component,Input,ElementRef } from "#angular/core"
#Component({
selector: "Dummy-Selector",
template: `Hello Dummy How Are you....`,
// inputs: ["rating"]
})
export class DummyComponent {
debugger;
#Input() username: string;
}
LoginComponent.html
<input type="text" [(ngModel)]="LoginObj.username" value="user" />
<div>
<Dummy-Selector [username]='LoginObj.username'></Dummy-Selector>
</div>
Here I'm getting my Dummy-selector username data but when I insert some data in LoginObj.username via the input field - why is it not reflected?

It's not clear exactly what error you are seeing (if any) but it input binding should work with the following:
LoginComponent.ts
#Component({..})
export class LoginComponent {
LoginObj = {};
}
In DummyComponent.ts change the template to show that the username field reflects changes from the input field.
import { Component,Input } from "#angular/core"
#Component({
selector: "Dummy-Selector",
template: `Hello Dummy How Are you... {{username}}`,
})
export class DummyComponent {
debugger;
#Input() username: string;
}

Related

How to reset primeng datepick calender

I am trying to reset primeng datepick calender but not working.I am working in angular 8.I have created custom datepicker component using primeng.I have given my code below.How to reset that?Anyone can have idea?please help to find the solution.
app.component.html:
<p-calendar dateformat="mm/dd/yyyy" [numberofmonths]="4" selectionmode="range" formControlName="datePick"></p-calendar>
<button (click)="resetdate()">Reset Date</button>
app.component.ts:
#ViewChild('p-calendar') calendar: any;
resetdate(){
this.calendar.value = null;
}
You are using reactive forms, in the reactive form it will set with form control setValue method.
Update: You can provide model value as an array.
component.html
<hello name="{{ name }}"></hello>
<div [formGroup]="myGroup">
<p>
Date Reset
</p>
<p-calendar formControlName="date" selectionMode="range" [readonlyInput]="true"></p-calendar>
<button (click)="reset()">Reset</button>
<button (click)="setCustomDateRange()">Set Custom Date Range</button>
</div>
component.ts
import { Component } from '#angular/core';
import { FormControl , FormGroup} from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
yearRange = '2000:2020';
myGroup: any;
rangeDates: Date[];
constructor(){
this.myGroup = new FormGroup({
date: new FormControl('')
});
}
setCustomDateRange(){
var date = new Date();
date.setDate(date.getDate() + 10);
this.myGroup.get('date').setValue([new Date(), date]);
}
reset(){
console.log(this.myGroup.get('date').value)
this.myGroup.get('date').setValue(null);
}
}
check working code
Use [(ngModel)] as below:
<p-calendar [(ngModel)]="value"></p-calendar>
and in ts use:
value: Date;
resetdate() {
this.value = null;
}
See working code
If necessary, like for me, you can destroy and recreate the component like this :
<p-calendar *ngIf="showCalendar"></p-calendar>
<button (click)="resetdate()">Reset Date</button>
detectChanges() method apply *ngIf and destroy the component:
constructor(private changeDetectorRef: ChangeDetectorRef) { }
showCalendar = true;
resetdate(): void {
this.showCalendar = false;
this.changeDetectorRef.detectChanges();
this.showCalendar = true;
}
no need to create separate method to reset data binding on module. just use property showClear="true" on tag
<p-calendar [(ngModel)]="value" [showClear]="true"></p-calendar>
for reference check documentation

Conditionally change date format of owl-date-time picker in angular

I using owlDateTime(https://daniel-projects.firebaseapp.com/owlng/date-time-picker) picker in may project.
After date selected it shows the mm/dd/yyyy format but I want to change this format to dd/mm/yyyy conditionally.
bellow are my code
.component.html
<input [max]="max" [owlDateTimeTrigger]="dt_date_time" [owlDateTime]="dt_date_time" formControlName="date_time" id="date_time" type="text" class="form-control date-picker date-field hasDatepicker" placeholder="dd/mm/yyyy" name="date_time" value="">
<owl-date-time [pickerType]="'calendar'" #dt_date_time></owl-date-time>
I have solve above problem using following code
import { Component, OnInit } from '#angular/core';
import { DateTimeAdapter } from 'ng-pick-datetime';
#Component({
selector: 'app-home-layout',
templateUrl: './home-layout.component.html',
styleUrls: ['./home-layout.component.css']
})
export class HomeLayoutComponent implements OnInit {
constructor(dateTimeAdapter: DateTimeAdapter<any>) {
let UserAttributes=JSON.parse(localStorage.getItem('UserAttributes'));
let country= UserAttributes['custom:country'];
if(country=='USA'){
dateTimeAdapter.setLocale('us');
}else{
dateTimeAdapter.setLocale('en-IN');
}
}
ngOnInit() {
}
}

Programmatically open an N level self nested mat-menu component with matMenuTrigger openMenu

I am trying to make a self nested component that uses Angular Material mat-menu. I have a flyoutcomponent that is a wrapper for flyout-menu-item component, that will have a button as a matMenuTrigger for the nested component that will appear as many levels as the FeatureInput.FeatureChoices dictates. FeatureInput is an object that has FeatureChoices that may or may not contain other featurechoices etc N levels deep. Below code does not compile but it should demonstrate what I am doing. Basically I have flyout menu component as a input to a form and I am trying to load a stored answer on a form rather than select new, which I can do easily using the nested component. The desired behavior is that if the user clicks top matMenuTrigger button to open the top menu that it would expand all child menus to the menu item that matches with the FeatureInput.FeatureValue and sets the menu item _highlighted to true. I am using the menuOpen input parameter and ngChanges successfully to find the match(with I a setTimeout which cannot be right). Basically when I console.log this.trigger it is undefined. Ideally in the ngOnChange to the openMenu I would go through all menus and call openMenu on all the triggers but I cannot get access to the matMenuTrigger with ViewChild as the docs say. I get undefined. *-( All help welcome please and thanks.
Here is flyout template component.
<div>
<buttonmat-button [matMenuTriggerFor]="menu.childMenu"
(onMenuOpen)="onMenuOpen()"
(onMenuClose)="onMenuClose()">
<span [innerHTML]="featureInput.Text"></span>
</button>
<app-flyout-menu-item #menu
[featureChoicesObject]="featureInput.FeatureChoices"></app-flyout-menu-item>
</div>
And here is its .ts
import { Component, OnInit, Input, ViewChild } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
#Component({
selector: 'app-flyout',
templateUrl: './flyout.component.html',
styleUrls: ['./flyout.component.scss']
})
export class FlyoutComponent implements OnInit {
#Input() featureInput: FeatureInput
constructor() { }
ngOnInit() {
}
onMenuOpen() {
this.menuOpen = true;
}
onMenuClose() {
this.menuOpen = false;
}
}
And here is flyout-menu-item template
<mat-menu #childMenu="matMenu" [overlapTrigger]="false">
<span *ngFor="let featureChoice of featureChoices">
<span>
<button mat-menu-item [matMenuTriggerFor]="menu.childMenu">
<span [innerHTML]="featureChoice.Text"></span>
</button>
<app-flyout-menu-item #menu
[menuOpen]="menuOpen"
[featureInput]="featureInput"
[featureChoicesObject]="featureChoice.FeatureChoices"
(onOptionSelected)="someService.SomeMethod($event)"></app-flyout-menu-item>
</span>
<span *ngIf="!featureChoice.FeatureChoices">
<button mat-menu-item (click)="selectOption(featureChoice.ID)" [innerHTML]="featureChoice.Text" value="{{featureChoice.ID}}"></button>
</span>
</span>
</mat-menu>
And here is its .ts
import { Component, OnInit, Input, Output, ViewChild, EventEmitter, OnChanges, SimpleChanges } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
import { FeatureChoice } from 'app/model/feature-choice';
import { FeatureInput } from 'app/model/feature-input';
#Component({
selector: 'app-flyout-menu-item',
templateUrl: './flyout-menu-item.component.html',
styleUrls: ['./flyout-menu-item.component.scss']
})
export class FlyoutMenuItemComponent implements OnInit{
#ViewChild('menu') public menu;
#ViewChild('childMenu') public childMenu;
#ViewChild(MatMenuTrigger) public trigger: MatMenuTrigger;
#Input() featureInput: FeatureInput;
#Input() featureChoicesObject: FeatureChoice;
#Output() onOptionSelected: EventEmitter<FeatureInput> = new EventEmitter<FeatureInput>();
constructor(public solutionDataService: SolutionDataService) { }
ngOnInit() {
console.log(this.trigger);
}
ngOnChanges(simpleChanges: SimpleChanges) {
if (simpleChanges.menuOpen && simpleChanges.menuOpen.currentValue) {
setTimeout(() => {
// console.log(this.menu);
const itemsArray = this.childMenu.items.toArray();
for (let x = 0; x < itemsArray.length; x++) {
const menuItem = itemsArray[x];
if (this.featureInput.FeatureValue !== '' && menuItem._elementRef.nativeElement.value === this.featureInput.FeatureValue) {
menuItem._highlighted = true;
}
}
}, 1);
}
}
}
this.menuOpen = true;
Perhaps add menuOpen: boolean = false as an attribute at the top of your FlyoutComponent. I don't know where the value of menuOpen is saved.
the menuOpen property relates to the matMenuTrigger.
here's an example:
<button [ngClass]="{'active-icon': trigger.menuOpen}" type="button" mat-
icon-button #trigger="matMenuTrigger" [matMenuTriggerFor]="help">
<mat-icon></mat-icon>
</button>
<mat-menu #help="matMenu">
<div> textId </div>
</mat-menu>

typescript in ASPNET core 2 with angular - acces html document

I've searched a while for this but I feel like this is one of the basics so no one bothers to explain it anymore...
Here's my problem.
I'm writing a component in TypeScript, which is part of an ASPNET core 2 and angular project.
TS file :
import { Component } from '#angular/core';
#Component({
selector: 'clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent{
rows: Array<any>;
constructor() {
let btn = document.getElementById("coolbutton");
if (btn === null) return;
btn.addEventListener("click", (e: Event) => this.ClickMeButton());
}
ClickMeButton() {
alert("toto");
}
}
HTML file :
<input type="button" value="Click" id="coolbutton"/>
But an error is raised when the page loads :
An unhandled exception occurred while processing the request.
NodeInvocationException: Uncaught (in promise): ReferenceError: document is
not defined
I am unable to find any explanations on how to import document in my TS componenet...
just put the (click) on the element and call your function:
import { Component } from '#angular/core';
#Component({
selector: 'clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent{
constructor() {}
public clickMeButton(): void {
alert("toto");
}
}
<input type="button" value="Click" (click)="clickMeButton()"/>

Angular2: get value of input in dynamic form

I need to get value of a certain input in my dynamic form.
I have JSON parameters like this
{
"etiquette":"Téléphone mobile",
"ordre":1,
"obligatoire":true,
"pattern":"^(?:(?:(?:\\\\+|00)33[ ]?(?:\\\\(0\\\\)[ ]?)?)|0){1}[1-9]{1}([ .-]?)(?:\\\\d{2}\\\\1?){3}\\\\d{2}$",
"section":"TelMail",
"type":"text",
"nom":"telephoneMobile",
"texteIndice":"Téléphone mobile"
}
,
{
"etiquette":"Mail",
"ordre":2,
"obligatoire":true,
"pattern":"(?:[a-zA-Z0-9!#$%&''*+=?^_`{|}~-]+(?:\\\\.[a-zA-Z0-9!#$%&''*+=?^_`{|}~-]+)*|\u201d(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21\\\\x23-\\\\x5b\\\\x5d-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])*\u201d)#(?:(?:[a-zA-Z0-9àâäçéèëêîïôôûüù](?:[a-zA-Z0-9-àâäçéèëêîïôôûüù]*[a-zA-Z0-9àâäçéèëêîïôôûüù])?\\\\.)+[a-zA-Z0-9àâäçéèëêîïôôûüù](?:[a-zA-Z0-9-àâäçéèëêîïôôûüù]*[a-zA-Z0-9àâäçéèëêîïôôûüù])?|\\\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21-\\\\x5a\\\\x53-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])+)\\\\])",
"section":"TelMail",
"type":"email",
"nom":"mail",
"texteIndice":"Mail"
},
{
"etiquette":"Type alerte",
"ordre":3,
"obligatoire":true,
"options": [{
"code" : "SMS",
"valeur" : "Alertes SMS"
},
{
"code" : "MAIL",
"valeur" : "Alertes Mail"
}],
"section":"Alerte",
"type":"radio",
"nom":"typeAlerte",
"texteIndice":"Type alerte"
}
I have Interface like below screenshot.
I customised radio component to contain radio input and input for mail and phone.
What I need is: get value of input phone/mail and put in in the input related to the radio.
Here is my radio component:
import {Component,Inject,Input} from '#angular/core';
import {NgForm, FormGroup} from '#angular/forms';
import {ExtraFormField} from '../model/form';
import {ExtraField} from './extra-field';
import { CatalogueService } from "../../catalogue/catalogue.service";
#Component({
selector: 'radio-extra-field',
template:`
<div class="form-group" >
<label [attr.for]="field.nom">{{field.etiquette}}</label>
<div *ngFor="let option of field.options" >
<input type="radio" name ="{{field.nom}}" value="{{option.code}}" id="{{option.code}}" [(ngModel)]="typeSelectionne">{{option.valeur}}
<input id="{{option.code}}" [attr.title]="field.etiquette" [attr.minlength]="field.longueurMin" [attr.min]="field.min" [attr.max]="field.max"
[attr.maxlength]="field.longueurMax" [attr.value]="field.valeur"
[attr.type]="text" [formControl]="fieldControl" (change)="maj(id.value)"
[attr.id]="option.code" type="text" [attr.disabled]="typeSelectionne != option.code? disabled : null ">
<error-messages [control]="field.nom"></error-messages>
</div>
<error-messages [control]="field.nom"></error-messages>
</div>
`
})
export class RadioExtraField extends ExtraField {
typeSelectionne: string;
#Input() field:ExtraFormField;
#Input() entity:{fields:Object};
#Input() formGroup:FormGroup;
constructor(public catalogueService: CatalogueService, #Inject(NgForm) formDir: NgForm) {
super(null, catalogueService, formDir);
}
get disabled():string {
if(this.field) {
return 'disabled';
}
return null;
}
}
Is there a way to do this ?
thank you
You can use
(ngModelChange)
what it do is it will call function ,there you can assign value to ngModel of input field.

Resources