what is parent stand in selector in angular 2 - angular2-select

import { Component, Input } from "#angular/core";
import "./loadingSpinner.component.css!";
#Component({
selector: "loading-spinner-Parent",
template: `
<div *ngIf="showSpinner" class="loader-directive-wrapper">
<div class="loader"></div>
</div>`
})
export class LoadingSpinnerComponent {
#Input() public showSpinner: boolean = false;
}

Related

`#ngrx/store` - createFeatureSelector never called from wrapper component

Here is my createFeatureSelector ts file :
import { State } from "./../../state/app.state";
import { EventState, ModelEvent } from "./../models/model.event";
import { createFeatureSelector, createSelector, ActionReducerMap } from "#ngrx/store";
export interface NewState extends State {
events:EventState
}
const getCalendarFeatureState = createFeatureSelector<EventState>("reducer");
export const getEvents = createSelector(getCalendarFeatureState, state => state.events );
my events shell component ( where i call the getEvents ):
import { Component, OnInit, ChangeDetectionStrategy } from '#angular/core';
import { Store, select } from '#ngrx/store';
import { Observable } from 'rxjs';
import * as fromRoot from "./../../state";
import { CalendarActions, Load } from "./../../state/calendar.actions";
import { ModelEvent, EventState } from "./../../models/model.event";
#Component({
selector: 'calendar-shell',
templateUrl: './calendar-shell.component.html',
changeDetection:ChangeDetectionStrategy.OnPush
})
export class CalendarShellComponent implements OnInit {
events$:Observable<any>
constructor(private store:Store<fromRoot.NewState>) { }
ngOnInit():void{
this.store.dispatch(new Load());
this.events$ = this.store.pipe(select(fromRoot.getEvents)); //getting nothing!!
}
}
template :
<div *ngIf="events$ | async"> //shows nothing!!
<ul>
<li *ngFor="let item of events">{{item.title}}</li>
</ul>
</div>
Any help? thanks in advance. ( ready to provide further details if any )
I update the dom element like this:
<div *ngIf="events$ | async"> //shows nothing!!
<ul>
<li *ngFor="let item of events | async">{{item.title}}</li>
</ul>
</div>
works fine.

How to Validate Angular 2 FormArray for length and Regex

app.component.ts
import { Component,OnInit } from '#angular/core';
import {FormControl,FormGroup,FormArray,FormBuilder} from '#angular/forms'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
form=new FormGroup({
topics:new FormArray([])
})
addTopic(topic:HTMLInputElement){
(this.form.get('topics') as FormArray).push(new FormControl(topic.value));
topic.value='';
}
}
app.component.html
<form>
<input type="text" class="form-control" (keyup.enter)="this.addTopic(topic)" #topic />
<ul class="list-group">
<li class="list-group-item" *ngFor="let topic of form.get('topics').controls">
{{topic.value}}
</li>
</ul>
</form>
I have created a Multi Input Control using Angular FormArray but how can i Validate the same for Minimum 2 Items(Length=2) and only accept integer values.
How to Add Validators.minlength like Reactive Form / Model Driven Form Approach.
How can i get those items using ngModel?
I hope this helps.
import {
Component,
OnInit
} from '#angular/core';
import {
FormControl,
FormGroup,
FormArray,
FormBuilder
} from '#angular/forms'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 6';
form = new FormGroup({
topics: new FormArray(this.formBuilder.control(''), [Validators.reqired, Valiadtors.minlength(2)], Validators.Paterrn("^[0-9]*$"))
])
addTopic(topic: HTMLInputElement) {
(this.form.get('topics') as FormArray).push(new FormControl(topic.value));
topic.value = '';
}
}

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>

Angular 4 - update list after delete

I am building a site for upcoming concert events. When I create a new event I got it to save to the backend (Ruby on Rails) and immediately display the new event in the event list. However, when I delete an event, the event gets deleted in the database but the front end does not refresh.
event-create.component.ts
import { Component, OnDestroy, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from "#angular/forms";
import { EventService } from "../event.service";
import { Event } from "../event";
import { Venue } from "../../venue/venue";
import { VenueService } from "../../venue/venue.service";
import { ActivatedRoute, Router} from '#angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap/datepicker'
import { DataService } from '../../data.service';
#Component({
selector: 'app-event-create',
templateUrl: './event-create.component.html',
styleUrls: ['./event-create.component.scss']
})
export class EventCreateComponent implements OnInit {
id: number;
event: Event;
venues: Venue[];
bsValue: Date = new Date();
date: string;
time: string;
datepickerModel: Date = new Date();
bsConfig: Partial<BsDatepickerConfig>;
eventTime: Date = new Date(this.bsValue.getFullYear(), this.bsValue.getMonth(), this.bsValue.getDay(), 19, 0, 0, 0);
mstep: number = 15;
eventForm: FormGroup;
constructor(private route: ActivatedRoute,
private router: Router,
private eventService: EventService,
private venueService: VenueService,
private data: DataService,
fb: FormBuilder) {
this.eventForm = fb.group({
'title': [null, Validators.required],
'venue': [1, Validators.required],
'date': null,
'time': null,
'description': [null, Validators.required]
});
this.bsConfig = Object.assign({}, { containerClass: 'theme-red' });
}
ngOnInit(): void {
this.getVenues();
}
getVenues(){
this.venueService.query().subscribe(
venues => {
this.venues = venues;
},
err => {
console.log(err);
}
);
}
onSubmit() {
Object.keys(this.eventForm.controls).forEach(field => {
const control = this.eventForm.get(field);
control.markAsTouched({ onlySelf: true });
});
if (this.eventForm.valid) {
let date: Date = new Date(this.eventForm.controls['date'].value);
let time: Date = new Date(this.eventForm.controls['time'].value);
let event: Event = new Event(
null,
this.eventForm.controls['venue'].value,
this.formatTimestamp(date, time),
this.eventForm.controls['title'].value,
this.eventForm.controls['description'].value
);
this.eventService.save(event).subscribe();
this.data.addEvent(event);
this.router.navigate(['/event']);
}
}
formatTimestamp(date: Date, time: Date): number {
let timezoneOffset: number = time.getTimezoneOffset() / 60;
if((time.getHours() + timezoneOffset) > 23){
date.setDate(date.getDate() + 1);
}
date.setUTCHours(time.getUTCHours());
date.setUTCMinutes(time.getMinutes());
date.setUTCSeconds(time.getSeconds());
return date.getTime();
}
redirectUserPage() {
this.router.navigate(['/user']);
}
}
event-index.component.ts
import { Component, OnInit } from '#angular/core';
import { Event } from '../event';
import { EventService } from '../event.service';
import { Router } from '#angular/router';
import { DataService } from '../../data.service';
import { Output, EventEmitter } from '#angular/core';
#Component({
selector: 'app-event-index',
templateUrl: './event-index.component.html',
styleUrls: ['./event-index.component.scss']
})
export class EventIndexComponent implements OnInit {
#Output()
someEvent = new EventEmitter();
event: Event;
private events: Event[];
constructor(
private router: Router,
private eventService: EventService,
private data: DataService
) { }
ngOnInit() {
this.getEvents();
this.data.currentEvent.subscribe(event => this.event = event);
}
getEvents(){
this.eventService.query().subscribe(
events => {
this.events = events;
},
err => {
console.log(err);
}
)
}
newEvent(){
this.router.navigate(['/event/create']);
}
editEvent(event: Event){
if(event){
this.router.navigate(['/event/edit', event]);
}
}
deleteEvent(event: Event){
let index = this.events.indexOf(event);
if(index > -1){
this.eventService.delete(event).subscribe(
event => {
this.events.slice(index, 1);
}
);
}
}
}
data.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Event } from './event/event';
#Injectable()
export class DataService{
currentEvent: BehaviorSubject<Event> = new BehaviorSubject<Event>(null);
public addEvent(newEvent: Event): void{
this.currentEvent.next(newEvent);
}
}
event-create.component.html
<div class="row justify-content-center">
<h1>New Event</h1>
</div>
<div class='row justify-content-center'>
<div class='col-6'>
<form [formGroup]='eventForm' (ngSubmit)="onSubmit(eventForm.value)">
<div class='form-group'>
<label>Title</label>
<input type="text" class='form-control' [ngClass]="{'is-invalid': eventForm.controls['title'].invalid && eventForm.controls['title'].touched}" formControlName="title">
<div *ngIf="eventForm.controls['title'].hasError('required')" class="invalid-feedback">Title is required</div>
</div>
<div class='form-group'>
<label>Description</label>
<textarea formControlName="description" class='form-control' [ngClass]="{'is-invalid': eventForm.controls['description'].invalid && eventForm.controls['description'].touched}"></textarea>
<div *ngIf="eventForm.controls['description'].hasError('required')" class="invalid-feedback">Description is required</div>
</div>
<div class='form-group'>
<label>Venue</label>
<select class='form-control' formControlName='venue'>
<option *ngFor="let venue of venues" [value]="venue.id">{{venue.name}}</option>
</select>
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" bsDatepicker [bsConfig]="bsConfig" [(ngModel)]="datepickerModel" formControlName='date'>
</div>
<div class='form-group'>
<label>Time</label>
<timepicker [(ngModel)]="eventTime" [minuteStep]="mstep" formControlName='time'></timepicker>
</div>
<button type="submit" class='btn btn-default'>Submit</button>
<pre>{{eventForm.value | json}}</pre>
</form>
</div>
</div>
event.service.ts
import { Injectable } from '#angular/core';
import { Event } from './event';
import { HttpClient } from '#angular/common/http';
import { Response } from '#angular/http';
import { Observable } from 'rxjs/Observable'
#Injectable()
export class EventService {
private apiUrl = 'http://localhost:3000/events';
constructor(private http: HttpClient) {}
query(): Observable<any>{
return this.http.get(this.apiUrl);
}
get(id: number): Observable<Event>{
return null;
}
save(event: Event): Observable<any>{
return this.http.post(this.apiUrl, event);
}
delete(event: Event): Observable<any>{
console.log(event);
return this.http.delete(this.apiUrl + '/' + event.id)
}
update(event: Event): Observable<Event>{
return null;
}
}
You are using slice() where you should be using splice() in deleteEvent()
Try changing:
this.events.slice(index, 1);
To
this.events.splice(index, 1);

How to use routing of angular2 and .net mvc Routing

I am doing authentication and authorization of pages on the server side. on index pages of each controller. But inside each index page I want to use angular 2 hence I want to use angular 2 routing.
I have tried like
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:''
})
export class AppComponent {
}
app.module.ts
import {NgModule} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { RouterModule } from '#angular/router'
import { TestSuiteComponent } from './testsuite/testsuite.component'
//import {InputTextModule, CalendarModule, DataTable} from 'primeng/primeng';
import { DataTableModule, SharedModule } from 'primeng/primeng';
#NgModule({
imports: [BrowserModule, DataTableModule, SharedModule, RouterModule.forRoot([
{
path: 'TestSuiteEditor/Index',
component: TestSuiteComponent
},
{
path: 'Home/Index',
component: TestSuiteComponent
}
])],
declarations: [AppComponent,TestSuiteComponent],
bootstrap: [ AppComponent]
})
export class AppModule { }
on testsuite.component.ts page
import { Directive, Component, OnInit } from '#angular/core';
import {DataTableModule, SharedModule} from 'primeng/primeng';
import { TestSuite } from './testsuite';
#Component({
// moduleId: module.id,
selector: 'testsuite-header',
template: `
<div class="ui-widget-header ui-helper-clearfix" style="padding:4px 10px;border-bottom: 0 none">
<i class="fa fa-search" style="float:left;margin:4px 4px 0 0"></i>
<input #gb type="text" pInputText size="50" style="float:left" placeholder="Global Filter">
</div>
<div class="ui-datatable ui-widget">
<div class="ui-datatable-tablewrapper">
<p-dataTable [value]="testSuites" [rows]="5" [paginator]="true" [globalFilter]="gb" [editable]="true">
<p-column field="testSuiteId" header="TestSuites (startsWith)" [style]="{'width':'10%'}" [filter]="true" [editable]="true"></p-column>
<p-column field="projectId" header="ProjectId (contains)" [style]="{'width':'10%'}" [filter]="true" filterMatchMode="contains" [editable]="true"></p-column>
<p-column field="name" header="Name (startsWith)" [style]="{'width':'30%'}" [filter]="true" [editable]="true"></p-column>
<p-column field="description" header="Description (endsWith)" [style]="{'width':'40%'}" [filter]="true" filterMatchMode="endsWith" [editable]="true"></p-column>
<p-column field="isActive" header="IsActive (endsWith)" [style]="{'width':'10%'}" [filter]="true" filterMatchMode="endsWith" [editable]="true"></p-column>
</p-dataTable>
</div>
</div> `,
// providers: [TestSuiteService]
})
export class TestSuiteComponent{}
Home/Index.cshtml
<testsuite-header>Loading....</testsuite-header>
but it throwing an error of
Cannot find primary outlet to load 'TestSuiteComponent'
You have forgotten to add router-outlet in your application. You can define router-outlet in AppComponent like this-
<router-outlet></router-outlet>
So your AppComponent will looks like this-
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:`
<!-- Routed views go here -->
<router-outlet></router-outlet>
`
})
export class AppComponent {
}
I have found the solution, thanks for your help
I have created the path similar to my MVC routing and added in routing.ts.
Since angular 2routing have feature of loading the active url so it automatically loads the component which is assign to that URL.

Resources