Angular list reference not getting updated on item deletion - javascript

I am implementing a feature which displays the selected items from a hierarchy structure, on the right.
slice.component.ts :
import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '#angular/core';
import * as API from '../../shared/api-routes';
import { DataService } from '../../shared/service/data.service';
import { TreeNode } from '../../shared/dto/TreeNode';
import { Subject } from 'rxjs/Subject';
import html from './slice.component.html';
import css from './slice.component.css';
#Component({
selector: 'slice-component',
template: html,
providers: [DataService],
styles: [css],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SliceComponent {
selections: TreeNode<string>[] = [];
newList: TreeNode<string>[];
constructor(dataService:DataService, cd:ChangeDetectorRef) {
super(dataService, cd);
}
public onSliceChange(event:TreeNode<string>):void {
if(event.selected) {
this.selections.push(event);
}
else {
var index = this.selections.indexOf(event);
if(index > -1) {
this.selections.splice(index, 1);
}
}
this.newList = this.selections.slice();
}
}
slice.component.html :
<p>Slices</p>
<mat-input-container>
<input #searchInput matInput placeholder="Search for Slices">
</mat-input-container>
<div class="flex-container">
<div class="SliceCheck" *ngIf="isDataLoaded">
<fortune-select
(sliceSelected)="onSliceChange($event)">
</fortune-select>
</div>
<div class="sendToRight">
<rightside-component
[sliceTreeNode]="newList">
</rightside-component>
</div>
</div>
rightside.component.ts :
import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '#angular/core';
import { TreeNode } from '../../shared/dto/TreeNode';
import html from './rightside.component.html';
import css from './rightside.component.css';
#Component({
selector: 'rightside-component',
template: html,
providers: [DataService],
styles: [css],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RightSideComponent {
#Input() sliceTreeNode: TreeNode<string>[];
constructor(private cd: ChangeDetectorRef) {}
getSlices() : TreeNode<string>[] {
if (typeof(this.sliceTreeNode) == "undefined" || (this.sliceTreeNode) === null) {
return [];
}
return this.sliceTreeNode;
}
deselect(item: TreeNode<string>): void {
if((item.children) !== null) {
item.children.forEach(element => {
this.deselect(element);
});
}
var index = this.sliceTreeNode.indexOf(item);
if(index > -1) {
this.sliceTreeNode.splice(index, 1);
}
item.selected = false;
}
}
rightside.component.html :
<ul class="selection-list" >
<li *ngFor="let item of getSlices()">
<button class="btn" (click)="deselect(item)" *ngIf="item.selected">
<i class="fa fa-close"> {{ item.displayName }} </i>
</button>
</li>
</ul>
In my implementation, everything works as expected until the following happens :
You delete an item from the rightside list, it gets deselected correctly from the hierarchy. But when you select it again from the hierarchy, it shows up twice in the side-view list now.
Somehow the list instance in the right-side component does not get updated when a node is selected again which has been previously deselected.
Any inputs on how to fix this? It is something similar to this plunkr I found online : http://next.plnkr.co/edit/1Fr83XHkY0bWd9IzOwuT?p=preview&utm_source=legacy&utm_medium=worker&utm_campaign=next&preview

The most likely issue is that you're using ChangeDetectionStrategy.OnPush and performing mutations within onSliceChange of the SliceComponent without an explicit call to cd.markForCheck().
Either remove changeDetection: ChangeDetectionStrategy.OnPush from SliceComponent or add cd.markForCheck() to the end of onSliceChange
When you set the change detection to OnPush, Angular only guarantees that the component will be updated when the references passed to it's Inputs are changed. onSliceChange doesn't replace any Input, so the slice component won't be updated.
You should also consider replacing deselect in RightSideComponent with an Output and handling the changes in SliceComponent. The convention of one-way data flow is to only modify common state in the common parent. This prevents conflicts when two components both want to modify some shared state.

Related

How to update parent component view when data is fetched from child component?

I have a parent and a child component, the child component is actually a modal where we can enter emails and click on 'Add to List'.
The entered emails are then fetched from parent component using #ViewChild property. The array details are obtained in parent because I can console.log() and see them from parent.
But how do I update a part of view in Parent with this new data is received ?
The code and explanations are as below :
Child component :
"emails" is an array with email ids.
I am fetching this array from child.
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'app-add-student-popup',
templateUrl: './add-student-popup.component.html',
styleUrls: ['./add-student-popup.component.scss']
})
export class AddStudentPopupComponent implements OnInit {
emails: string[] = [];
constructor() { }
ngOnInit(): void {
}
**** Some other code that adds user entered emails to an array 'emails' ****
----
----
sendData() {
console.log(this.emails);
}
}
Parent
import { AfterViewInit, Component, OnInit, ViewChild } from '#angular/core';
// Add students modal popup
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal/';
import { AddStudentPopupComponent } from './add-student-popup/add-student-popup.component';
#Component({
selector: 'app-create-course',
templateUrl: './create-course.component.html',
styleUrls: ['./create-course.component.scss']
})
export class CreateCourseComponent implements OnInit, AfterViewInit {
bsModalRef!: BsModalRef;
emails: string[] = [];
isEmpty: boolean = true;
#ViewChild(AddStudentPopupComponent) addStudent!: AddStudentPopupComponent;
constructor(private modalService: BsModalService) { }
ngOnInit(): any {}
ngAfterViewInit(): void {
if (this.addStudent) {
this.emails = this.addStudent.emails;
isEmpty = false;
}
}
openAddStudentModal() {
this.bsModalRef = this.modalService.show(AddStudentPopupComponent, {class: 'modal-lg'});
this.bsModalRef.content.closeBtnName = 'Close';
}
}
I want to use the updated "emails" array in my front end view. The view part using this array should be updated.
View part
When the popup is filled and submitted the emails array is populated and it should update the this view part.
<div class="multipleInput-container" *ngIf="!isEmpty;else noEmails">
<div class="col-lg-12">
<ul *ngFor="let email of emails">
<li class="multipleInput-email">{{ email }}</li>
</ul>
</div>
</div>
<ng-template #noEmails>
<div class="col-lg-3">
<input type="text" class="form-control form-control-sm"
placeholder="No Students Added" aria-label="No Students Added">
</div>
</ng-template>
Thanks in Advance
You should use #Output
In AddStudentPopupComponent
emails: string[] = [];
#Output() sendEmail = new EventEmitter();
sendData() {
this.sendEmail.emit(this.emails);
}
then in create-course.component.html file
<app-add-student-popup (sendEmail)="emails = $event"></app-add-student-popup>

How can I access an already transcluded ContentChild?

I have a angular component app-b that is used within a component app-a that is used in the app-component. The app-component has some content in app-a, app-a transcludes this with ng-content into app-b, app-b shows it with another ng-content - but how can I access this content within the component (and not it's template)?
I would think that ContentChild is the correct approach but appears to be wrong.
Example:
https://stackblitz.com/edit/angular-ddldwi
EDIT: Updated example
You cannot query by tag name with #ContentChild decorator. You can query either by template variable, component or directive selector.
app-a.component.html
<app-b>
<ng-content></ng-content>
<p #myContent>This is a content child for app-b.</p>
</app-b>
app-b.component.ts
import { Component, AfterContentInit, ContentChild } from '#angular/core';
#Component({
selector: 'app-b',
templateUrl: './b.component.html',
styleUrls: ['./b.component.css']
})
export class BComponent implements AfterContentInit {
#ContentChild('myContent') contentchild;
ngAfterContentInit() {
console.log(this.contentchild);
}
}
Live demo
I recommend sharing the data between components. For example, move your data (E.G. dummyName) into a service. Then add the service to each component (where you need the shared data).
Service:
import { Injectable } from '#angular/core';
#Injectable()
export class DataShareService {
public dummyName: String = 'one';
constructor() { }
}
Add the new service to app.module.ts:
providers: [DataShareService],
Child Component:
import { DataShareService } from './data-share.service';
import { Component } from '#angular/core';
#Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent {
constructor(public ds: DataShareService) { }
toggle() {
this.ds.dummyName = this.ds.dummyName === 'one' ? 'two' : 'one';
}
}
Child Component template (html):
<p> {{ds.dummyName}}</p>
<button (click)="toggle()">Click Me to Toggle Value</button>
Parent Component:
import { Component, OnInit } from '#angular/core';
import { DataShareService } from './data-share.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(public ds: DataShareService) {}
displayNumber() {
return this.ds.dummyName === 'one' ? 1 : 2;
}
}
Parent Component template (html):
<p> this is the parent component:</p>
<div> value as string: {{ ds.dummyName }} </div>
<div> value as number: <span [textContent]="displayNumber()"></span></div>
<hr>
<p> this is the child component:</p>
<app-child></app-child>
Note! The child component toggle() function demonstrates how you can change the data. The parent component displayNumber() function demonstrates how to use the data, independent of it's display (I.E. as just pure data).
This appears to be impossible due to a bug in Angular:
https://github.com/angular/angular/issues/20810
Further reference:
https://www.reddit.com/r/Angular2/comments/8fb3ku/need_help_how_can_i_access_an_already_transcluded/

Angular2, toggle a checked checkbox list

Is there a way to toggle a checked checkbox list in Angular2?
I have a button that when pressed and the full list is in view, it will show only the checked items in the list. When the button is pressed again, it will show the entire list.
Plunkr: http://plnkr.co/edit/jZz4XoHjYJ40bjt2eOU5?p=preview
//our root app component
import {Component, NgModule} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<li *ngFor="let col of data" class="form-group">
<input type="checkbox" name="col" value="{{col.value}}" [(ngModel)]="col.value" (change)="addColumns(col)" />{{col.name}}
</li>
`,
})
export class App {
name:string;
data:any[]=[{"id":"13","name":"AAA"},{"id":"15","name":"BBB"},{"id":"20","name":"CCC"}]
constructor() {
this.name = 'Angular2'
}
get selectedcheckboxes() {
return this.data
.filter(opt => opt.value)
}
addColumns(col){
this.selectedcheckboxes;
console.log(this.selectedcheckboxes)
}
}
#NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
HTML:
<body>
<my-app>
loading...
</my-app>
<button class="check">Collapse/Expand</button>
</body>
In Angular1, it looks like this: http://jsfiddle.net/jzhang172/of4yy8k9/ I'm looking to do the same thing in Angular2, but can't understand the syntax.
You can put the main array in other variable and then just change the data variable according your clicked button (to expand or to collapse), you may need one variable to define if it's full list or the selected list
something like:
isFullList: boolean;
mainData: Array<any> = [your main data here];
data: Array<any> = [data to use in list]; //should initied by mandata
toggle() {
//this.isFullList: boolean
if (!this.isFullList) {
this.data = [...this.mainData];
} else {
this.data = [...this.selectedcheckboxes];
}
console.log(this.data)
this.isFullList = ! this.isFullList
}
plunker: http://plnkr.co/edit/V1iiX87gYVMUtIkmpMfT?p=preview
You can implement an filter at your component, and invoke the filter at your template.
In the filter, just add a flag to control to filter or show original list, and toggle the flag by click the button.
Invoke filter at template
*ngFor="let col of getData()"
Filter data in component
getData() {
return this.filter ? this.data.filter(item => item.value === true) : this.data;
}
Plunker Demo

Change component's template Angular 2

I'm using mdl-select component. It's a drop-down list. When you press it there are focusin event fired. But it doesn't when you press an arrow-dropdown icon, so I needed to change a template a bit to have a desired behavior. But it's a library component. Is there a way to override it's template?
The thing I need to change just to add tabindex=\"-1\" to element. I can do it with js, but I use component a lot in app, and I don't want to use document.getElement... every time I use MdlSelectComponent in the views of my own components.
I tried to use #Component decorator function on MdlSelectComponent type, however it requires to declare this class once again and anyway have done nothing.
Update
main.browser.ts
/*
* Angular bootstraping
*/
import { Component } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { decorateModuleRef } from './app/environment';
import { bootloader } from '#angularclass/hmr';
import {MdlSelectComponent} from '#angular2-mdl-ext/select';
/*
* App Module
* our top level module that holds all of our components
*/
import { AppModule } from './app';
/*
* Bootstrap our Angular app with a top level NgModule
*/
export function main(): Promise<any> {
console.log(MdlSelectComponent)
MdlSelectComponent.decorator.template = "<div class=\"mdl-textfield is-upgraded\" [class.is-focused]=\"this.popoverComponent.isVisible || this.focused\" [class.is-disabled]=\"this.disabled\" [class.is-dirty]=\"isDirty()\"> <span [attr.tabindex]=\"!this.disabled ? 0 : null\" (focus)=\"open($event);addFocus();\" (blur)=\"removeFocus()\"> <!-- don't want click to also trigger focus --> </span> <input #selectInput tabindex=\"-1\" [readonly]=\"!autocomplete\" class=\"mdl-textfield__input\" (click)=\"toggle($event)\" (keyup)=\"onInputChange($event)\" (blur)=\"onInputBlur()\" [placeholder]=\"placeholder ? placeholder : ''\" [attr.id]=\"textfieldId\" [value]=\"text\"> <span class=\"mdl-select__toggle material-icons\" (click)=\"toggle($event)\"> keyboard_arrow_down </span> <label class=\"mdl-textfield__label\" [attr.for]=\"textfieldId\">{{ label }}</label> <span class=\"mdl-textfield__error\"></span> <mdl-popover [class.mdl-popover--above]=\"autocomplete\" hide-on-click=\"!multiple\" [style.width.%]=\"100\"> <div class=\"mdl-list mdl-shadow--6dp\"> <ng-content></ng-content> </div> </mdl-popover> </div> ";
return platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(decorateModuleRef)
.catch((err) => console.error(err));
}
// needed for hmr
// in prod this is replace for document ready
bootloader(main);
APP.COMPONENT.TS
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { Router } from '#angular/router';
require('../../../styles/styles.scss');
import {MdlSelectComponent} from '#angular2-mdl-ext/select';
//
declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';
#Component({
selector: 'app',
encapsulation: ViewEncapsulation.None,
styleUrls: [],
template: `
<div>
<mdl-select [(ngModel)]="personId">
<mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
</mdl-select>
<router-outlet></router-outlet>
</div>`
})
export class AppComponent implements OnInit {
constructor(
router: Router,
) {
router.events.subscribe(data => {
scrollTo(0, 0);
});
}
public ngOnInit() {
}
}
As #angular2-mdl-ext/select uses Reflect to define decorators then you do the following
declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';
Plunker Example

Making a reusable angular2 component that can be used anywhere on the a site

Use Case: When making asynchronous calls, I want to show some sort of a processing screen so that end users knows something is happening rather than just staring at the screen. Since I have multiple places throughout the site where I want to use this, I figured making it a component at the "global" level is the best approach.
Problem: Being slightly new to angular2, I'm not getting if this is a problem of it being outside the directory in which the main component exists and the OverlayComponent being in another location or if I'm just all together doing it wrong. I can get the component to work fine but I need to be able to call functions to hide/destroy the component and also display the component. I have tried making it a service but that didn't get me any further so I'm back to square one. Essentially my question revolves around building a reusable component that has methods to hide/show itself when invoked from whatever component it's being called from.
Below is my current code:
Assume OverlayComponent.html is at /public/app/templates/mysite.overlay.component.html
Assume OverlayComponent.ts is at /public/app/ts/app.mysite.overlay.component
Assume mysite.tracker.component is at \public\app\ts\pages\Tracker\mysite.tracker.component.ts
OverlayComponent.html
<div class="overlay-component-container">
<div class="overlay-component" (overlay)="onShowOverlay($event)">
<div>{{processingMessage}}</div>
<div>
<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
</div>
</div>
</div>
OverlayComponent.ts
import { Component } from '#angular/core';
#Component({
selector: 'overlay-component',
templateUrl: '/public/app/templates/mysite.overlay.component.html',
styleUrls: ['public/app/scss/overlay.css']
})
export class OverlayComponent {
onShowOverlay(e) {
$('.overlay-component').fadeIn(1000);
}
hideOverlay(e) {
$('.overlay-component').fadeOut(1000);
}
}
TrackerComponent.ts
import { Component, Output, OnInit, EventEmitter } from '#angular/core';
import { Http } from '#angular/http';
import { TrackerService } from './Tracker.service';
import { MenuCollection } from "./MenuCollection";
import { Menu } from "./Menu";
#Component({
moduleId: module.id,
selector: 'tracker-component',
templateUrl: '/public/app/templates/pages/tracker/mysite.tracker.component.html',
styleUrls: ['../../../scss/pages/racker/tracker.css'],
providers: [TrackerService]
})
export class TrackerComponent implements OnInit{
MenuCollection: MenuCollection;
#Output()
overlay: EventEmitter<any> = new EventEmitter();
constructor(private http: Http, private TrackerService: TrackerService) {
let c = confirm("test");
if (c) {
this.onShowOverlay();
}
}
ngOnInit(): void {
this.MenuCollection = new MenuCollection();
this.MenuCollection.activeMenu = new Menu('Active Menu', []);
this.TrackerService.getTrackerData().then(Tracker => {
this.MenuCollection = Tracker;
this.MenuCollection.activeMenu = this.MenuCollection.liveMenu;
console.log(this.MenuCollection);
},
error => {
alert('error');
})
}
onShowOverlay() { //This doesn't seem to 'emit' and trigger my overlay function
this.overlay.emit('test');
}
}
At a high level, all I'm wanting to do is invoke a components function from another component. Thanks in advance for any helpful input
You can use the #ContentChild annotation to accomplish this:
import { Component, ContentChild } from '#angular/core';
class ChildComponent {
// Implementation
}
// this component's template has an instance of ChildComponent
class ParentComponent {
#ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
// Do stuff with this.child
}
}
For more examples, check out the #ContentChildren documentation.

Categories

Resources