I am trying to bind some data but is not working on
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template : `<child [in]="25"></child>`
})
export class AppComponent {}
and the child component
import { Component, Input } from '#angular/core';
#Component({
selector: 'child',
template: '<h1>{{in}}</h1>',
})
export class ChildComponent {
#Input() in: string;
}
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template : <child [in]="25"></child>
})
export class AppComponent {}
import { Component, Input } from '#angular/core';
#Component({
selector: 'child',
template: '{{in}}',
})
export class ChildComponent {
#Input() in: string;
}
Nothing wrong in this code .. every thing is working fine.
You have two ways of assigning values to an input of a component:
1) Either by passing directly the string value to the input from the template:
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template : `<child in="25"></child>`
})
export class AppComponent {}
2) Or by binding the input to a variable defined in your class:
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template : `<child [in]="myVar"></child>`
})
export class AppComponent {
public myVar: string = "25";
}
As a result you cannot bind the input to a numeric variable as you did here, simply because a variable defined in a class cannot be numeric (but it surely can be alphanumeric).
You should actually assign a variable and then refer it. public Hello = "25";
Then [in]="this.hello"
OR
Remove the brackets and assign directly
in ="25";
Related
I have added input decorator in child component ts file and I am trying to access it from app component(parent), but I am not getting it.Error : Property 'name' has no initializer and is not definitely assigned in the constructor.
Hellocomponent.ts
import { Component, Input, OnInit } from '#angular/core';
#Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.scss']
})
export class HelloComponent implements OnInit {
#Input() name:string;
constructor() { }
ngOnInit(): void {
}
}
appcomponent.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
styles: [`
/* p{color: blue;}*/
`]
})
export class AppComponent {
title = 'Angular';
counter = 0;
}
App component.html
<h1>#Input</h1>
<app-hello [name]="title"></app-hello>
I am fairly new to the Angular world and working on angular 7, I am doing some examples where components share data within, The Parent to child part working fine but when i am trying to send any values from child to parent it's not working.
It shows me this error
app-component.html
<div>{{show}}</div>
<app-communicating-components [Parent]="message" (childEvent)="getMessage($event)"></app-communicating-components>
app-component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'AngularLesson2';
public message = 'Hello my child, Parents here';
public show: string;
getMessage($event) {
this.show = $event;
}
}
communicating-components.component.html
<p>
{{Parent}}
</p>
<button (click)="fireEvent()">Fire from child</button>
communicating-components.component.ts
import { Component, OnInit, Input, Output } from '#angular/core';
import { EventEmitter } from 'events';
#Component({
selector: 'app-communicating-components',
templateUrl: './communicating-components.component.html',
styleUrls: ['./communicating-components.component.css']
})
export class CommunicatingComponentsComponent implements OnInit {
#Input() Parent;
#Output() public childEvent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
fireEvent() {
this.childEvent.emit('Hi, I am child');
console.log("event fire" + this.childEvent);
}
}
What am I doing wrong here?
I believe the problem is in your import import { EventEmitter } from 'events'; is not the one you should import here. Try changing the import to import { EventEmitter } from '#angular/core';
UPDATE
Here's a stackblitz example showing that it works
With Angular newer versions, like 8 you have to:
Import correctly Emitter as k.s. said:
import { EventEmitter } from '#angular/core'
Initialize the emitter for Output:
#Output()
emisor = new EventEmitter<type>();
This question already has answers here:
How to communicate between component in Angular?
(8 answers)
Closed 5 years ago.
I want to pass value from one component to another component.
i.e., I need to pass value from Dashboard Component to Header Component
Here is my Dashboard Component
import{Component}from '#angular/core';
import { Header } from '../../layout/header.component';
export class Dashboard{
showAlert(id : any)
{
setItem(id);
}
}
Here is my Header component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'header',
templateUrl: './header.component.html',
})
export class Header{
public setItem(id : any)
{
console.log('Exported value'+id)
}
}
But it is always giving Cannot find setItem
What is the mistake i am doing and how can i fix this ?
Note : I am doing this in Angularjs 2
If the element raises events, you can listen to them with an event binding. Refer to the angular doc https://angular.io/guide/template-syntax#event-binding for in depth knowledge.
Dashboard Component
import{Component}from '#angular/core';
import { Header } from '../../layout/header.component';
#Component({
selector: 'dashboard',
templateUrl: './dashboard.component.html',
})
export class Dashboard{
#Output() setItemEvent = new EventEmitter();
showAlert(id : any)
{
this.setItemEvent.emit(id);
}
}
Header component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'header',
template: '<dashboard (setItemEvent)="setItem(param)"></dashboard>',
})
export class Header{
public setItem(id : any)
{
console.log('Exported value'+id)
}
}
You can use:
localStorage.setItem('name', 'value');
where name is the variable name you will use to access the value. You can access the value using:
var x = localStorage.getItem('name');
You can use event-binding like this :
////First Component
#component({
selector:'componentA',
})
export class ComponentA{
yourMethod(yourPassedParameter:any){...}
}
////// Second Component
#component({
selector:'componentB',
template: `<button (click)="yourMethod(yourParameter)">click</button>`
)
export class ComponentB{
#Output() eventLis = new EventEmitter();
yourMethod(yourParameter:any){...
this.eventLis.emit(yourData);
}
}
////Your crosscomponent
#component({
selector:'crosscomponent',
template: `<componentA #componentA></componentA>
<componentB (eventLis)="componentA.yourMethod(yourParameter)"></componentB>`
)
export class crosscomponent{
}
I'm trying to limit the search of my dependencies to only its host by using #Host.
But it's not working without ng-content or transclusion.
The below code is not working(without ng-content)
// Root Component
#Component({
selector: 'my-app',
template: '<parent></parent>'
})
export class RootComponent { }
#Component({
selector: 'parent',
template: '<child></child>',
providers:[{provide:TestService,useClass:TestService}]
})
export class ParentComponent {
name: string = '';
constructor(abc:TestService){
abc.name='SomeName';
this.name=abc.name
}
}
#Component({
selector: 'child',
template: '<h1>{{parent}}</h1>'
})
export class ChildComponent {
parent: string = ""
constructor(#Host() testService: TestService) {
this.parent= 'My parent is :'+testService.name;
}
}
With ng-content
Now just by changing the templates in RootComponent & the ParentComponent the above code starts working
#Component({
selector: 'my-app',
template: '<parent><child></child></parent>'
})
export class RootComponent { }
#Component({
selector: 'parent',
template: '<ng-content></ng-content>',
providers:[{provide:TestService,useClass:TestService}]
})
export class ParentComponent {
name: string = '';
constructor(abc:TestService){
abc.name='SomeName';
this.name=abc.name
}
}
#Component({
selector: 'child',
template: '<h1>{{parent}}</h1>'
})
export class ChildComponent {
parent: string = ""
constructor(#Host() testService: TestService) {
this.parent= 'My parent is :'+testService.name;
}
}
Questions:
Why the first code not working(without ng-content)..?
#Host can only works with ng-content..?
What difference ng-content makes as the structure of the compiled HTML is same in both the cases.
Here are the Plunker for reference:
Not working
It looks like you need to use viewProviders instead of providers to work with #Host as also shown in #Host
Plunker example
I am trying to make import a service inside a component but when I call the Input coming from this service, in my template, it does not render anything.
Here is my entity:
export interface PageState {
step: string;
}
export class SimplePageState implements PageState {
step: string;
}
Here is my service:
import { Injectable } from '#angular/core';
import { PageState } from './state.entity';
#Injectable()
export class PageStateService {
getPageState(): Promise<PageState[]> {
const step = [{ 'step': '1' }];
return Promise.resolve(step);
// return this.http.get('/api/status');
}
}
I am importing and instantiating these in my main component:
import { Component, OnInit } from '#angular/core';
import { Module } from '../modules/core/module.entity';
import { ModuleService } from '../modules/core/module.service';
import { PageState } from './state.entity';
import { PageStateService } from './state.service';
#Component({
selector: 'df-esign',
templateUrl: './esign-page.html',
styleUrls: ['./esign-page.scss'],
providers: [ ModuleService, PageStateService ]
})
export class EsignComponent implements OnInit {
modules: Module[];
pageState: PageState[];
constructor(private moduleService: ModuleService, private pageStateService: PageStateService) { }
getModules() {
this.moduleService.getModules().then(modules => this.modules = modules);
}
getPageState() {
this.pageStateService.getPageState().then(pageState => this.pageState = pageState);
}
ngOnInit() {
this.getModules();
this.getPageState();
}
}
And finally, I am using SimplePageState inside of a particular component, this way:
import { Component, Input } from '#angular/core';
import { SimpleModule } from '../core/module.entity';
import { SimplePageState } from '../../core/state.entity';
#Component({
selector: 'df-module-page',
templateUrl: './module-page.html',
styleUrls: ['./module-page.scss'],
})
export class ModulePageComponent {
#Input() module: SimpleModule;
#Input() pageState: SimplePageState;
}
But trying to do {{pageState}} in my template gives me a blank result with no error.. Anybody can help? I've spent hours looking on the internet and trying to make it work.
Edit:
I am trying to use it inside a bread-crumbs component.
Here is the beginning of my module-view.html, which contains df-module-page as well as df-module-bread-crumbs:
<ng-container [ngSwitch]="module.type">
<template [ngSwitchCase]="'PageModule'"><df-module-page [module]="module" [pageState]="pageState"></df-module-page></template>
<template [ngSwitchCase]="'TextModule'"><df-module-text [module]="module"></df-module-text></template>
<template [ngSwitchCase]="'BreadCrumbModule'"><df-module-bread-crumb [module]="module" [pageState]="pageState" class="{{module.class}}"></df-module-bread-crumb></template>
I am calling SimplePageState in the bread-crumb-component too:
import { Component, Input, HostBinding } from '#angular/core';
import { SimpleModule } from '../core/module.entity';
import { SimplePageState } from '../../core/state.entity';
#Component({
selector: 'df-module-bread-crumb',
templateUrl: './module-bread-crumbs.html',
styleUrls: ['./module-bread-crumbs.scss']
})
export class ModuleBreadCrumbsComponent {
#Input() module: SimpleModule;
#Input() pageState: SimplePageState;
}
And I am trying to do an ngIf inside of module-breads-crumbs.html with a pageState condition which does not have any effect:
<div class="dfbreadcrumbs">
<ol *ngIf="module">
<li *ngFor="let crumb of module.slots.crumbs; let i = index" class="step_{{i + 1}}">{{crumb.text}}</li>
</ol>
</div>
<div *ngIf="pageState">ohohoh</div>
To pass data to an input you would need something like
<df-module-page [pageState]="pageState">
in the template of EsignComponent