I'm trying to create a seat reservation application with datepicker. initially all the messages are seen on an alert, but I decided to move them to the dialogs.
as you know better than me to create the dialog you have to create a new component. the problem is that, I can't pass the date that is captured in the first component inside a method that formats the date.
how can I do?
I am attaching the relevant codes
appcomponent.html:
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Prenota</mat-label>
<input matInput [matDatepicker]="picker" [(ngModel)]="this.datari.myFormattedDates" (dateChange)="openDialog($event)">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker [dateClass]="dateClass()" #picker> </mat-datepicker>
</mat-form-field>
appcomponent.ts:
export class AppComponent implements OnInit {
dateOfBirth = Date();
pipe = new DatePipe('it-IT');
currentDate = moment().format('DD/MM/YYYY');
datari: MyConst = new MyConst();
openDialog(event) {
//catch date
this.dateOfBirth = event.value;
//I format the date
this.datari.myFormattedDates = this.pipe.transform(this.dateOfBirth, 'dd/MM/yyyy');
// open dialog
this.dialog.open(DialogComponent );
}
dialogcomponent.ts:
export class DialogComponent implements OnInit {
dialogTitle = 'Parking';
dialogMessage = 'do you want to book for' + '?' ;
constructor(public dialog: MatDialog, public dialogRef: MatDialogRef<DialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
}
dialogcomponent.html:
<h3 mat-dialog-title>{{dialogTitle}}</h3>
<div mat-dialog-content>
{{dialogMessage}}
</div>
<div style="float:right;margin:20px;">
<input style="margin:0px 10px;" type="button" value="confirm" [mat-dialog-close]="true">
<input type="button" value="cancel" [mat-dialog-close]="false">
</div>
thanks a lot to everyone :)
You will be able to pass data through the open method like this :
this.dialog.open(DialogComponent, {
data: { date: this.datari.myFormattedDates },
// Others options
// width: ...
// height: ...
// panelClass: ...
});
And in your dialog component :
constructor(public dialog: MatDialog, public dialogRef: MatDialogRef<DialogComponent>, #Inject(MAT_DIALOG_DATA) public data: { data: any }) { }
ngOnInit() {
console.log(this.data.date);
}
Take a look at https://material.angular.io/components/dialog/overview
Related
I have angular code something like this: and I want to populate checkbox ticked for the option which are default selected
export class InformationComponent implements OnInit{
dataIds: FormControl;
#Input()
requestBody:Request;
requestForm: FormGroup;
constructor(private _formBuilder: FormBuilder){}
ngOnInit(){
this.dataIds = new FormControl(this.requestBody.dataIds);
this.requestForm = this._formBuilder.group({
dataIds: this.dataIds;
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<form [formGroup]="reqForm" #mainForm>
<div>
<app-data-list [dataIds]="dataIds" [disabled]="disabled"> </app-data-list>
</div>
</form>
and below is my app-data-list component
export class EntityListComponent implemments OnInit, OnDestroy{
#Input()
public disabled:boolean;
public entitiesFilter:FormControl = new FormControl();
protected entityList = new RequestEntity[];
#Input()
public dataIds:FormControl;
#ViewChild('multiSelect', {static:true}) multiselect:MatSelect;
protected _onDestroy = new Subject<void>();
public filteredEntityList:ReplaySubject<RequestEntity[]> = new ReplaySubject<RequestEntity[]>
ngOnInit(){
this.myservice.getData().subscribe((resp:RequestEntity[])=>{
entityList = resp;
})
this.filteredEntityList.next(this.entityList.slice());
this.entitiesFilter.valueChanges.pipe(takeUntil(this._onDestroy)).subscribe(() => { this.filterEntitiesList();});
}
ngAfterViewInit(){
this.setInitialValue();
}
setInitialValue(){
this.filteredEntitiesList.pipe(take(1), takeUntil(_onDestroy)).subscribe(() => {
this.multiSelect.compareWith =(a:RequestEntity, b:RequestEntity) => a && b && a.entity == b.entity;
})
}
}
<div [formGroup]="form">
<mat-form-field>
<mat-label> Data ids</mat-label>
<mat-select [formControl]="dataIds" [multiple]="true" #multiSelect [disabled]="disabled">
<ngx-mat-select-search [formControl]="entitiesFilter" placeholderLabel="Search">
</ngx-mat-select-search>
<mat-option *ngFor="let entity of filterdEntitiesList |async" [value]"entity"> {{entity?.entity?.entityName}} </mat-option>
</mat-select>
</mat-form-field>
</div>
but my code is not pre populating the checked option against selected dataIds from back end but I had similar snippet in my code which does exactly same thing
I'm implementing alert services in my applications however I get the error Property 'alertService' does not exist on type 'AppComponent' and Property 'options' does not exist on type 'AppComponent'
app.component.html:
<div class="form-group">
<button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold"
(click)="alertService.success('Success!!', options)">Submit</button>
</div>
app.component.ts:
export class AppComponent {
public frmSignup: FormGroup;
public message = "Congrats you have successfully created your account";
constructor(private fb: FormBuilder) {
this.frmSignup = this.createSignupForm();
}
createSignupForm(): FormGroup {
return this.fb.group(
{
........
}
);
}
submit() {
// do signup or something
console.log(this.frmSignup.value);
alert(this.message);
}
You need to explicity inject the alertService in the constructor of AppComponent
constructor(private fb: FormBuilder, alertService: AlertService) {
this.frmSignup = this.createSignupForm();
this.alertService = alertService;
}
The options need to be set as well in the Component as a public property.
However:
The better option would be to create a class method, that you can call on click event:
<div class="form-group">
<button [disabled]="frmSignup.invalid" type="submit" class="btn btn-primary btn-block font-weight-bold"
(click)="handleClick()">Submit</button>
</div>
export class AppComponent {
public frmSignup: FormGroup;
public message = "Congrats you have successfully created your account";
options = {};
constructor(private fb: FormBuilder, private alertService: AlertService) {
this.frmSignup = this.createSignupForm();
}
createSignupForm(): FormGroup {
return this.fb.group(
{
........
}
);
}
submit() {
// do signup or something
console.log(this.frmSignup.value);
alert(this.message);
}
handleClick() {
this.alertService.success('Success!!', options);
}
}
Note: I don't understand, why the submit button doesn't call the submit method...
I have a component in which [(ngModel)]=attrProps._value is getting set on user input and also getting value when already present by default.
Now there is a button which leads to a toggle button for value option when the user wants to have custom value.
But when the user clicks on the refresh button the value in the input field should get clear?
#Component({
selector: 'n-customValue',
template: `
<mat-form-field class="inputfield-attr-view">
<input matInput [(ngModel)]="attrProps._value" placeholder="{{bKeeperService.getAttributeType(attrProps).displayAs}}">
<mat-icon matSuffix (click)="revertIcon()" class="editButton">
<img class="attributeview-button" src="../../assets/icons/refresh.svg">
</mat-icon>
</mat-form-field>
`
})
export class customValueComponent implements OnInit {
#Output() clickEvent: EventEmitter<string> = new EventEmitter<string>();
constructor(public myservice: customService) { }
ngOnInit(): void { }
revertIcon() {
this.clickEvent.emit('REVERT_EVENT');
}
}
I tried using element ref but could not solve it.
#Component({
selector: 'n-customvalue',
template: `
<mat-form-field class="inputfield-attr-view">
<input matInput [(ngModel)]="attrProps._value" #searchInput placeholder="{{bKeeperService.getAttributeType(attrProps).displayAs}}">
<mat-icon matSuffix (click)="revertIcon()" class="editButton">
<img class="attributeview-button" src="../../assets/icons/refresh.svg">
</mat-icon>
</mat-form-field>
`
})
export class customvalueComponent implements OnInit {
#Output() clickEvent: EventEmitter<string> = new EventEmitter<string>();
#Input('nAttrProps') nAttrProps;
#ViewChild('searchInput') searchInput: ElementRef;
attrPropsValue;
constructor(public myservice: customService) { }
ngOnInit(): void { }
revertIcon() {
this.clickEvent.emit('REVERT_EVENT');
this.searchInput.nativeElement.value = '';
}
}
I recently learned Angular2. Currently, I have got a material modal after some searching. However,I can't find how I return the data that the user can input.
In the modal I currently have, there is one input field and one checkbox. When close the console logs "de dialog closed" and "true".
This is my modal HTML:
<h2 mat-dialog-title>Add Group</h2>
<mat-dialog-content>
<div>
<mat-form-field>
<input matInput placeholder="Groupname">
</mat-form-field>
<mat-form-field>
<mat-checkbox >Private group?</mat-checkbox>
</mat-form-field>
<mat-form-field>
<button mat-raised-button color="primary">img</button>
</mat-form-field>
</div>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button mat-dialog-close>cancel</button>
<!-- The mat-dialog-close directive optionally accepts a value as a result for the dialog. -->
<button mat-button [mat-dialog-close]="true" >save</button>
</mat-dialog-actions>
TS code:
import { Component, OnInit, Inject } from '#angular/core';
import { GroupsService} from '../../../services/Groups.service';
import { Groups } from '../../../models/groupModel'
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '#angular/material';
#Component({
selector: 'app-groups',
templateUrl: './groups.component.html',
styleUrls: ['./groups.component.scss'],
})
export class GroupsComponent implements OnInit {
animal: string;
name: string;
groups: Groups[];
constructor(
private groupsService: GroupsService,
public dialog: MatDialog
){}
ngOnInit() {
this.groupsService.getMyGroups()
.then(group =>{
this.groups = group;
console.log(this.groups)
}).catch(error=>{
console.log(error);
});
}
openDialog(): void {
let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
height: '300px',
width: '300px',
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);
this.animal = result;
});
}
testgroup(id){
console.log(id)
}
acceptGroup(){
console.log('accept')
}
declineGroup(){
console.log('decline');
}
createGroup(){
console.log("sample");
}
}
#Component({
selector: 'dialog-overview-example-dialog',
templateUrl: './model.html',
})
export class DialogOverviewExampleDialog {
constructor(
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
onNoClick(): void {
this.dialogRef.close();
}
}
This part of your code inside HTML template is currently responsible for what you're passing back from the model: [mat-dialog-close]="true". As you see you're just passing true and nothing else. Simplest way to achieve what you want is to create form inside the dialog and pass its value.
<h2 mat-dialog-title>Add Group</h2>
<mat-dialog-content>
<form #modalForm="ngForm">
<div>
<mat-form-field>
<input matInput name="groupName" placeholder="Groupname" ngModel>
</mat-form-field>
<mat-form-field>
<mat-checkbox name="privateGroup" ngModel>Private group?</mat-checkbox>
</mat-form-field>
<mat-form-field>
<button mat-raised-button color="primary">img</button>
</mat-form-field>
</div>
</form>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button mat-dialog-close>cancel</button>
<button mat-button [mat-dialog-close]="modalForm.value">save</button>
</mat-dialog-actions>
You can also pass form value on submit (using (ngSubmit)="mySubmitFunction(modalForm.value)" on form tag ) to the mySubmitFunction defined in DialogOverviewExampleDialog. And then, after some kind of validation for example, pass data by using: this.dialogRef.close(someVariableContainingValues).
use this code i think it will be work:
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);
//this.animal = result;
}).()=>{
this.animal = result;
};
I'm new to Angular2 and spent a lot of time trying to fix a simple thing.
As you can see, I only want to access the Local Storage (bottom function, ui())and send the contents to the View, Register.components.html. I tried various blog but I failed every-time.
So I can't really post an error, but how do I just access the local storage and display the contents to my view? Also ui() isn't being called. How do I call it?
Register.component.ts
import { Component, OnInit } from '#angular/core';
import {ValidateService} from '../../services/validate.service';
import {AlarmService} from '../../services/alarm.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
hours: String;
id: String;
constructor(
private validateService: ValidateService,
private FlashMessage: FlashMessagesService,
private Router: Router,
private AlarmService: AlarmService
){
}
ngOnInit() {
}
onRegisterSubmit(){
var user = {
hours: (new Date(this.hours.replace('T', ' ').replace('-', '/'))).valueOf(),
id: new Date().getTime(),
flag: 0
}
setTimeout(() => {
this.FlashMessage.show('Your alarm has been added.', {cssClass: 'alert-success', timeout: 5000});
}, 10);
var storage = localStorage.getItem('users');
var final = [];
if (storage == null || typeof(storage) == undefined )
{ final.push(user);
localStorage.setItem('users', JSON.stringify(final));
let time = new Date().getTime()
this.AlarmService.setUpAlarms(time);
}else{
var get = JSON.parse(localStorage.getItem('users'));
var size = Object.keys(get).length;
for(var i =0; i< get.length; i++){
final.push(get[i]);
}
final.push(user);
localStorage.setItem('users', JSON.stringify(final));
let time = new Date().getTime()
this.AlarmService.setUpAlarms(time);
}
}
ui(){
var storage = localStorage.getItem('users');
if (storage == null || typeof(storage) == undefined ){
var HERO = localStorage.getItem('users');
}
console.log(HERO);
const HEROES = HERO
}
}
This is my HTML view
<form (submit)="onRegisterSubmit()">
<div class = "container">
<div class="overlay">
<div id="alarm-dialog">
HEKK
<h2>Set alarm at</h2>
<div class="form-group">
<label class="hours">
<input type="datetime-local" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" class="form-control" [(ngModel)]="hours" name="hours" value="0" min="0" required/>
</label>
</div>
<a class="close"></a>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Set Alarm">
</div>
</form>
<tr *ngFor="let hero of heroes">
<td>{{hero.hours}}</td>
</tr>
If you want ui() called when the component loads, you can do it in ngOnInit:
ngOnInit() {
this.ui();
}
Also, declare heroes as a property on your component so it can be bound to the view:
export class RegisterComponent implements OnInit {
heroes: any[]; // Maybe add a type instead of "any"
// etc
}
And fix up your ui method a bit:
ui() {
this.heroes = JSON.parse(localStorage.getItem('users'));
}