I'm in Angular group project and I'm trying to implement delete functions for current workspace but I'm not sure how to do that. Any suggestion or help on how to do that?
Inside add-workspace.HTML file, I have a button that display a dialog box (delete-workspace-dialog).
Inside delete-workspace-dialog components file and there is a delete button. I'm trying use that button to delete current workspace.
Inside delete-workspace.dialog.ts file aka delete dialog box
export class DeleteWorkspaceDialogComponent implements OnInit {
constructor(
public dialogRef: MatDialogRef<DeleteWorkspaceDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit(): void {
}
onNoClick(): void {
this.dialogRef.close();
}
onDeleteClick(): void{
// Delete workspace here
}
}
I'm trying to use that "Yes,Delete it" button to delete the current workspace
Hope the below snippet might help:
In Delete pop up component:
import { WorkspaceService } from 'src/app/core/services/workspace.service';
export class DeleteWorkspaceDialogComponent implements OnInit {
constructor(
public dialogRef: MatDialogRef<DeleteWorkspaceDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any,
private workspaceService: WorkspaceService) { }
ngOnInit(): void {
}
onNoClick(): void {
this.dialogRef.close();
}
onDeleteClick(): void{
// Delete workspace here
this.workspaceService.deleteWorkspace(data.workspace).subscribe(response=>{
// Do some logic and close the popup
this.dialogRef.close();
},error=>{
// Error handling and close the popup
this.dialogRef.close();
})
}
}
From parent component to open delete popup:
HTML:
<button (click)="delete()">Delete</button>
TS:
delete(){
this.dialog.open(DeleteWorkspaceDialogComponent,{
data: {
workspace: this.workspace
}
});
}
Here you are passing the work space to be deleted and in delete popup, you are calling the service to delete the work space.
Hope it will help.
Related
I have two .ts files (editor.ts and editor_settings.ts), Corresponding to editor.ts i have creater editor.html file. Now what i am trying to call function inside editor_settings.ts on button click in editor.html.
editor.ts
import { EditorSetting } from '../app/editorSetting.component';
export class PadComponent implements OnInit, OnDestroy { ---- }
constructor(
private component: EditorSetting
) { }
submit() {
let userCode = this.component.editor.getValue();
console.log('Inside pad.componet.ts');
console.log(userCode);
}
editor.html
<button id="submit" type="button" class="btn btn-sm btn-run" (click)="submit()" [disabled]="loading"
style="background: #FF473A">
<i class="fa fa-play" aria-hidden="true"></i>
<span *ngIf="loading">Running</span>
<span else> Run </span>
</button>
Now, on button click in editor.html, i want to call function which is inside editor_settings.ts.
editor_settings.ts
export class EditorComponent implements OnInit, OnDestroy, OnChanges {--}
I am facing the following error:
inline template:0:0 caused by: No provider for EditorComponent!
To communicate two components that are not related to each other, you can use a service.
#Injectable({
providedIn: 'root',
})
export class YourService {
private yourVariable: Subject<any> = new Subject<any>();
public listenYourVariable() {
return this.yourVariable.asObservable();
}
public yourVariableObserver(value ?: type) {
this.yourVariable.next(value);
}
You import in yours components where you want use it this service.
import{ YourService } from ...
In Edit component :
submit(){
this.yourService.yourVariableObserver();
}
while in Editor_setting.ts
ngOnInit() {
this.sub=this.yourService.listenYourVariable().subscribe(
variable => {
this.callyourFunction();
}
)
}
Don't forget to unsubscribe to prevent memory leak
ngOnDestroy() {
this.sub.unsubscribe()
}
Another aproach valid if your editor is inside the editorSetting
<editor-setting>
<editor></editor>
</editor-setting>
Use Host in constructor
constructor(#Optional #Host() private component: EditorSetting) { }
I'm trying to catch paste event occuring on input fields.
It works perfectly on textarea and input but not on dropdowns. Select.
Here is my directive, the console.log is never called.
import { Directive, HostListener } from '#angular/core';
#Directive({ selector: '[catchPasteEvents]' })
export class CatchPastEvent {
#HostListener('onpaste') onPaste(event) {
console.log('Paste', event);
}
}
I created this directive that set a listener on document paste (as suggested by Sergey) but only when the select element is focused.
#Directive({ selector: 'select[selectPaste]' })
export class SelectPasteDirective implements OnDestroy {
#Output()
public paste: EventEmitter<ClipboardEvent> = new EventEmitter();
private listener: (event: ClipboardEvent) => void = this.handlePaste.bind(
this,
);
public ngOnDestroy(): void {
document.removeEventListener('paste', this.listener);
}
#HostListener('focus')
public onFocusedItem() {
document.addEventListener('paste', this.listener);
}
#HostListener('blur')
public onBlurItem() {
document.removeEventListener('paste', this.listener);
}
private handlePaste(event: ClipboardEvent) {
this.paste.emit(event);
}
}
Goodday, This is probably a nooby question but I can't get it to work.
I have a simple service which toggles an boolean, if the boolean is true the class active should appear on my div and if false no class.. Simple as that. But the boolean gets updated, but my view doesn't react to it. Do I somehow have to notify my view that something has changed ?
Service:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class ClassToggleService {
public menuActive = false;
toggleMenu() {
this.menuActive = !this.menuActive;
}
}
View (left menu component):
<div id="mainContainerRightTop" [class.active]="classToggleService.menuActive == true">
Toggle point (top menu component):
<a id="hamburgerIcon" (click)="classToggleService.toggleMenu()">
This because you are changing a value on a service not on the component, so Angular don't need to update the component, because it did not change. If you want to update the view of your component when a service element is modified, you have to use an Observables and Subjects, and subscribe to them. In this way when the element is changed, it automatically notify all the subscribed components.
#Injectable({
providedIn: 'root'
})
export class ClassToggleService {
public menuSubject: Subject<boolean> = new BehaviorSubject<boolean>(false);
public menuActive = this.menuSubject.asObservable();
toggleMenu(val : boolean) {
this.menuSubject.next(val);
}
}
And in your component just implement OnInit interface and subcribe to the observable in the your service:
public localBool = false;
ngOnInit() {
this._myService.menuActive.subscribe(value => this.localBool = value);
}
ComponentToggleMenu() {
this._myService.toggleMenu(!this.localBool);
}
Then your html:
<div id="mainContainerRightTop" [class.active]="localBool">
<a id="hamburgerIcon" (click)="ComponentToggleMenu()">
Why we need service, this should be integrated with component class. As a general rule, you are not supposed to call service method in template file.
export class TestComponent implements OnInit{
public menuActive = false;
toggleMenu() {
this.menuActive = !this.menuActive;
}
}
Template:
<div id="mainContainerRightTop" [class.active]="menuActive">
I can pass a class object like Person into a child component from parent component without any problems. But I would like to also manipulate that object in child component and pass it back to parent component.
This is the child component class:
export class ActionPanelComponent {
#Input('company') company: Company;
#Output() notify: EventEmitter = new EventEmitter();
constructor() {
}
public deleteCompany() {
console.log('display company');
console.log(this.company);
// FIXME: Implement Delete
this.company = new Company();
}
public onChange() {
this.notify.emit(this.company);
}
}
This is the html of this component (excerpt):
<div class="row" (change)="onChange()">
<div class="col-xs-2">
<button md-icon-button >
<md-icon>skip_previous</md-icon>
</button>
</div>
This is the parent component class (excerpt):
public onNotify(company: Company):void {
this.company = company;
}
And the parent component html (excerpt):
<action-panel [company]="company" (notify)="onNotify($event)"></action-panel>
I am doing something wrong because I cannot pass my company object inside the .emit and nothing works.
What is the correct way of achieving two way object binding between components?
Thanks in advance!
You were missing the type on the initialization of the EventEmitter.
You could use the Output binding to implement the two way object binding:
Child component (ts)
export class ActionPanelComponent {
#Input('company') company: Company;
#Output() companyChange: EventEmitter = new EventEmitter<Company>();
constructor() {
}
public deleteCompany() {
console.log('display company');
console.log(this.company);
// FIXME: Implement Delete
this.company = new Company();
}
public onChange() {
this.companyChange.emit(this.company);
}
}
Parent component (html)
<action-panel [(company)]="company"></action-panel>
So like this you don't need to declare an extra function onNotify. If you do need the onNotify function, use another name for the output binding:
export class ActionPanelComponent {
#Input('company') company: Company;
#Output() notify: EventEmitter = new EventEmitter<Company>();
constructor() {
}
public deleteCompany() {
console.log('display company');
console.log(this.company);
// FIXME: Implement Delete
this.company = new Company();
}
public onChange() {
this.notify.emit(this.company);
}
}
Change it like this to tell TS which Type the EventEmitter should emit:
export class ActionPanelComponent {
#Input('company') company: Company;
#Output() notify = new EventEmitter<Company>(); //<---- On this line!
constructor() {
}
public deleteCompany() {
console.log('display company');
console.log(this.company);
// FIXME: Implement Delete
this.company = new Company();
}
public onChange() {
this.notify.emit(this.company);
}
}
It is a workaround that worked for me, if it is helpful for anyone.
Your parent parent-component.ts would be like;
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'parent',
templateUrl:'./parent.component.html',
styleUrls: ['./parent.component.css']
})
export class Parent implements OnInit {
let parentInstance= this; //passing instance of the component to a variable
constructor() { }
parentMethod(var:<classtyepyourchoice>){
console.log(var);
}
ngOnInit() {
}
}
In you parent.component.html, you would have your child
<child [parent]="parentInstance" ></child>
This object will be available in the child component
Now, in your child component you will receive this like
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'child',
templateUrl:'./child.component.html',
styleUrls: ['./child.component.css']
})
export class Child implements OnInit {
#Input('parent') parent;
constructor() { }
childMethod(yourClassObject){
this.parent.parentMethod(yourClassObject);
}
ngOnInit() {
}
}
Thus, you can pass classobject from your child, like this, it worked for me.
I have a button on my nav bar (app.component.html) that I want to only show when the user is logged in.
This is my current approach that does not work for obvious reasons explained later. I want to find out how I can modify it to work.
Inside my app.component.html, I have the following button
<button *ngIf="isCurrentUserExist">MyButton</button>
Inside my app.component.ts, I am trying to bound the variable isCurrentUserExist to a function that returns true if the user exists.
I believe this is the problem because this code is only executed once at OnInit as oppose to somehow keeping the view updated
ngOnInit() {
this.isCurrentUserExist = this.userService.isCurrentUserExist();
}
For reference, inside my UserService.ts
export class UserService {
private currentUser: User
constructor(private http: Http,private angularFire: AngularFire) { }
getCurrentUser(): User {
return this.currentUser
}
setCurrentUser(user: User) {
this.currentUser = user;
}
isCurrentUserExist(): boolean {
if (this.currentUser) {
return true
}
return false
}
}
A bit more information about my app...
Upon start up when the user does not exist, I have a login screen (login component).
When the user logs in, it goes to firebase and grab the user information (async) and store it to my user service via
setCurrentUser(user: User)
So at this point, I like to update the button in my nav bar (which exists in app.component.html) and show the button.
What can I do to achieve this?
let's try this:
using BehaviorSubject
UserService.ts
import { Subject, BehaviorSubject} from 'rxjs';
export class UserService {
private currentUser: User;
public loggedIn: Subject = new BehaviorSubject<boolean>(false);
constructor(private http: Http,private angularFire: AngularFire) { }
getCurrentUser(): User {
return this.currentUser
}
setCurrentUser(user: User) { // this method must call when async process - grab firebase info - finished
this.currentUser = user;
this.loggedIn.next(true);
}
isCurrentUserExist(): boolean {
if (this.currentUser) {
return true
}
return false
}
}
app.component.ts
ngOnInit() {
this.userService.loggedIn.subscribe(response => this.isCurrentUserExist = response);
}
in app.component.ts you are assigned value from function once. So it will never change. To resolve this problem and to real time update use assign function instance of boolean variable this.isCurrentUserExist = this.userService.isCurrentUserExist;. And in view change change *ngIf expression as function isCurrentUserExist().