I am working on a code where I need to share the instance of the service. Here is the sample outline of the code where I am facing a trouble.
app.component.ts code:
import { Component } from '#angular/core';
import {ROUTER_DIRECTIVES} from '#angular/router';
import {HeaderComponent} from './header.component';
import {TotalContainer} from './container-total.component';
#Component({
selector: 'my-app',
template: `
<myheader [display]="display"></myheader>
<router-outlet></router-outlet>
`,
directives:[HeaderComponent,TotalContainer,ROUTER_DIRECTIVES]
})
export class AppComponent {
display = true;
}
My header component contains the nav-tabs which will update the
Now, one of the component which will replace the is container-total.component.ts
Now Inside the container-total.component.ts I have another component called bottom.component.
Here the code for container-total.component.ts
import {Component, OnInit} from '#angular/core';
import {BottomContainerComponent} from './bottom-container.component';
import {BlurredService} from '../services/blurred.service';
import {FollowUps} from '../properties/followups';
#Component({
selector:'container-total',
template:`
<div class="container" [class.blurred]="!display">
My Content of total container has to be blurred.
</div>
<bottom-container></bottom-container>
`,
styles:[`
.blurred{
-webkit-filter: blur(1px);
-moz-filter: blur(1px);
-o-filter: blur(1px);
-ms-filter: blur(1px);
filter: blur(1px) grayscale(90%);
}
`],
directives:[BottomContainerComponent],
providers:[BlurredService]
})
export class TotalContainer implements OnInit{
display;
constructor(private blurredService: BlurredService){
}
checkBlurr(){
this.display = this.blurredService.getService();
}
ngOnInit(){
this.checkBlurr();
}
}
Now, I am updating the value for the display in the bottom-container.component using the same service. Here is the code
bottom-container.component.ts
import {Component, Output, EventEmitter, OnInit} from '#angular/core';
import {BlurredService} from '../services/blurred.service';
#Component({
selector:'bottom-container',
template:`
<div class="container" [class.blurred]="!display" (click)="displayPopup()">
This is the bottom container needed to be blurred.
</div>
`,
styles:[`
.blurred{
-webkit-filter: blur(1px);
-moz-filter: blur(1px);
-o-filter: blur(1px);
-ms-filter: blur(1px);
filter: blur(1px) grayscale(90%);
}
`],
directives:[PopupComponent]
})
export class BottomContainerComponent implements OnInit{
display;
request:Requests = null;
constructor(private blurredService: BlurredService){
}
checkBlurr(){
this.display = this.blurredService.getService();
}
ngOnInit(){
this.checkBlurr();
}
displayPopup(){
this.blurredService.setService(false);
this.display = this.blurredService.getService();
}
}
Now, this is the service I have written.
blurred.service
import {Injectable} from '#angular/core';
#Injectable()
export class BlurredService{
display = true;
setService(value){
this.display = value;
}
getService(){
return this.display;
}
}
Now, When ever the div in bottom-container is getting clicked it is getting blurred. But not the div in the total-container, though I am updating the value through the service.
Should I call the function "checkBlurr" in total-container using EventEmitter from bottom-container. But if I do that, I might have more than one components in total-container for which I am going to implement the routing. Then how should I use the #Output and EventEmitter using the "".
Can any one help me with this?
You need to do something with your component interaction. The easiest thing would be to set the "display" property in your total component directly to the service:
<div class="container" [class.blurred]="!blurredService.getService()">
My Content of total container has to be blurred.
</div>
Related
I have created custom component DisplayTableComponent in my project. I want to incorporate Angular 4 Data table on my data for display purpose.
DisplayTableComponent.TS is as follows
import { Component, OnInit } from '#angular/core';
import { DataTableResource } from 'angular-4-data-table';
import { DataTableModule } from 'angular-4-data-table';
import persons from './data-table-demo1-data';
#Component({
selector: 'app-display-table',
templateUrl: './display-table.component.html',
styleUrls: ['./display-table.component.css']
})
export class DisplayTableComponent implements OnInit {
itemResource = new DataTableResource(persons);
items = [];
itemCount = 0;
constructor() {
this.itemResource.count().then(count => this.itemCount = count);
}
ngOnInit() {
}
reloadItems(params) {
// this.itemResource.query(params).then(items => this.items = items);
}
// special properties:
rowClick(rowEvent) {
console.log('Clicked: ' + rowEvent.row.item.name);
}
rowDoubleClick(rowEvent) {
alert('Double clicked: ' + rowEvent.row.item.name);
}
rowTooltip(item) { return item.jobTitle; }
}
My Html Template is as follows
<p>
display-table works!
</p>
<div style="margin: auto; max-width: 1000px; margin-bottom: 50px;">
<data-table id="persons-grid"
headerTitle="Employees"
[items]="items"
[itemCount]="itemCount"
(reload)="reloadItems($event)"
(rowClick)="rowClick($event)"
(rowDoubleClick)="rowDoubleClick($event)"
[rowTooltip]="rowTooltip"
>
<data-table-column
[property]="'name'"
[header]="'Name'"
[sortable]="true"
[resizable]="true">
</data-table-column>
<data-table-column
[property]="'date'"
[header]="'Date'"
[sortable]="true">
<ng-template #dataTableCell let-item="item">
<span>{{item.date | date:'yyyy-MM-dd'}}</span>
</ng-template>
</data-table-column>
<data-table-column
property="phoneNumber"
header="Phone number"
width="150px">
</data-table-column>
<data-table-column
[property]="'jobTitle'"
[header]="'Job title'"
[visible]="false">
</data-table-column>
<data-table-column
[property]="'active'"
[header]="'Active'"
[width]="100"
[resizable]="true">
<ng-template #dataTableHeader let-item="item">
<span style="color: rgb(232, 0, 0)">Active</span>
</ng-template>
<ng-template #dataTableCell let-item="item">
<span style="color: grey">
<span class="glyphicon glyphicon-ok" *ngIf="item.active"></span>
<span class="glyphicon glyphicon-remove" *ngIf="!item.active"></span>
</span>
</ng-template>
</data-table-column>
</data-table>
</div>
Now, The temporary source data file (data-table-demo1-data.ts) is as
export default [
{ 'name': 'Aaron 2Moore', 'email': 'aaa#aa.com', 'jobTitle': 'Regional Configuration Producer',
'active': true, 'phoneNumber': '611-898-6201', 'date': '2015-11-06T07:21:25.510Z' },
{ 'name': 'Yvonne Conroy Mrs.', 'email': 'sss#ssss.com', 'jobTitle': 'Global Mobility Orchestrator',
'active': false, 'phoneNumber': '115-850-0969', 'date': '2014-12-20T00:48:40.276Z' },
]
My app.Module.TS is as follows
import { BrowserModule } from '#angular/platform-browser';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { Routes, RouterModule} from '#angular/router';
import { DataTableModule } from 'angular-4-data-table';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MovieComponent } from './movie/movie.component';
import { DisplayTableComponent } from './display-table/display-table.component';
const appRoute: Routes =[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{path:'home', component:HomeComponent},
{path:'Movie', component:MovieComponent},
{path:'table', component:DisplayTableComponent},
];
#NgModule({
declarations: [
AppComponent,
HomeComponent,
MovieComponent,
DisplayTableComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoute)
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Could you please help me. I am getting below error
ERROR in ./node_modules/angular-4-data-table/src/index.ts
Module build failed: Error: C:\projects\Handson\website1\node_modules\angular-4-data-table\src\index.ts is missing from the TypeScript compilation. Please make sure
it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format
at AngularCompilerPlugin.getCompiledFile (C:\projects\Handson\website1\node_modules\#ngtools\webpack\src\angular_compiler_plugin.js:656:23)
at plugin.done.then (C:\projects\Handson\website1\node_modules\#ngtools\webpack\src\loader.js:467:39)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
# ./src/app/display-table/display-table.component.ts 13:29-60
# ./src/app/app.module.ts
# ./src/main.ts
# multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
It seems you are using angular 5 cli and need to integrate Angular 4 Data table on to your project.
My advice is to use angular5-data-table instead of version 4 if you are using angular 5.You can find it on https://www.npmjs.com/package/angular5-data-table
Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.
There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using #types) to no avail.
Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.
The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts
import { Component, OnInit } from "#angular/core";
import { StitchClientFactory } from "mongodb-stitch";
let appId = 'authapp-****';
#Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})
export class MongoAuthComponent implements OnInit {
mClient;
ngOnInit() {
this.mClient = StitchClientFactory.create(appId);
}
And you can then use this for whatever purpose you want, such as for implementing sign-in with Google
gLogin(){
this.mClient.then(stitchClient => {
stitchClient.authenticate("google");
})
not sure whether the question is still relevant considering it was asked two months ago but anyway...
As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any
For example:
declare var stitch: any;
export class MyService implements OnInit {
db;
client;
ngOnInit() {
this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
this.client.login();
}
save() {
this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
}
}
the previous answers are functional, but i wanna share a example using a service injectable.
service.ts
import { Injectable } from '#angular/core';
import { Jsonp, URLSearchParams } from '#angular/http';
import { StitchClientFactory } from "mongodb-stitch";
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private jsonp: Jsonp) { }
client;
connect(){
this.client = new StitchClientFactory.create("App ID"); // Slitch apps > Clients > App ID
this.client.then(stitchClient => stitchClient.login())
.then((stitchClient) => console.log('logged in as: ' + stitchClient))
.catch(e => console.log('error: ', e));
}
all() {
this.connect();
return this.client.then(stitchClient => {
let db = stitchClient.service('mongodb', 'mongodb-atlas').db("database Name"); // Slitch apps > mongodb-atlas > Name database.Collection
let itemsCollection = db.collection('name collection'); // Slitch apps > mongodb-atlas > Name database.Collection
console.log(itemsCollection.find().execute());
return itemsCollection.find().execute();
})
.then(result => {return result})
.catch(e => console.log('error: ', e));
}
}
after make the previous file, you must create a module to receive the data, so:
module.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { StitchClientFactory } from "mongodb-stitch";
import { Service } from 'service'; // previous code
declare var stitch: any;
#Component({
template: '
<ul class="demo-list-icon mdl-list">
<li class="mdl-list__item" *ngFor="let item of data | async">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-icon">{{propiedad.nombre}}</i>
</span>
</li>
</ul>
'
})
export class MainComponent implements OnInit {
data: Observable<[]>;
constructor(private Service: service) {
}
ngOnInit() {
this.propiedades = this.Service.all();
}
}
important, you don´t must forget to add service on module.ts intitial declarations.
mongodb Atlas
mongodb-stitch vía NPM
Documentation mongoDB Stitch.
Sure!
I am using 2.0.0-rc.6 in my angular 2 application.
on form submit I am getting this error - self.context.onSubmit is not a function
also it is appending form values in browser.
http://localhost:3000/register
on submit the page reloading and url become like this.
http://localhost:3000/register?firstName=vcvvc&lastName=vcv&userName=cvv&password=vcv&password=vcv
the codes are
form
<form class="ui form" (ngSubmit)="onSubmit()" #registrationForm="ngForm">
----
----
<button type="submit" class="ui button"> Register</button>
</form>
the service
import { Component } from '#angular/core';
import { User } from '../models/user';
import { RegisterService } from '../services/register.service';
#Component({
selector: 'side-panel',
templateUrl: 'app/components/register.component.html'
})
export class RegisterComponent {
newuser: User = new User();
theText: string;
constructor(private _registerService: RegisterService){
}
onsubmit(){
console.log('form submit clicked..');
this._registerService.sendUser(this.newuser).subscribe(
date =>{
this.newuser = new User();
},
error => console.log(error)
);
}
}
This error occurs when the name of the methods called in an event not matched with the template declaration and inside the class
In your template you have specified onSubmit() as camel case
<form class="ui form" (ngSubmit)="**onSubmit()**" #registrationForm="ngForm">
but inside the class, its not a camelCase "onsubmit()"
onsubmit(){
console.log('form submit clicked..');
this._registerService.sendUser(this.newuser).subscribe(
I have searched on the internet for this topic and I have found many different answer but they just do not work.
I want to make a real redirect with react-router to the '/' path from code. The browserHistory.push('/') code only changes the url in the web browser but the view is not refreshed by browser. I need to hit a refresh manually to see the requested content.
'window.location = 'http://web.example.com:8080/myapp/'' works perfectly but i do not want to hardcode the full uri in my javascript code.
Could you please provide me a working solution?
I use react ^15.1.0 and react-router ^2.4.1.
My full example:
export default class Logout extends React.Component {
handleLogoutClick() {
console.info('Logging off...');
auth.logout(this.doRedirect());
};
doRedirect() {
console.info('redirecting...');
//window.location = 'http://web.example.com:8080/myapp/';
browserHistory.push('/')
}
render() {
return (
<div style={style.text}>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick={this.handleLogoutClick.bind(this)}>Yes</Button>
</div>
);
}
}
You can use router.push() instead of using the history. To do so, you can use the context or the withRouter HoC, which is better than using the context directly:
import { withRouter } from 'react-router';
class Logout extends React.Component {
handleLogoutClick() {
console.info('Logging off...');
auth.logout(this.doRedirect());
};
doRedirect() {
this.props.router.push('/') // use the router's push to redirect
}
render() {
return (
<div style={style.text}>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick={this.handleLogoutClick.bind(this)}>Yes</Button>
</div>
);
}
}
export default withRouter(Logout); // wrap with the withRouter HoC to inject router to the props, instead of using context
Solution:
AppHistory.js
import { createHashHistory } from 'history';
import { useRouterHistory } from 'react-router';
const appHistory = useRouterHistory(createHashHistory)({
queryKey: false
});
export default appHistory;
Then you can use appHistory from everywhere in your app.
App.js
import appHistory from './AppHistory';
...
ReactDom.render(
<Router history={appHistory} onUpdate={() => window.scrollTo(0, 0)}>
...
</Router>,
document.getElementById('root')
);
Logout.js
import React from 'react';
import appHistory from '../../AppHistory';
import auth from '../auth/Auth';
import Button from "react-bootstrap/lib/Button";
export default class Logout extends React.Component {
handleLogoutClick() {
auth.logout(this.doRedirect());
}
doRedirect() {
appHistory.push('/');
}
render() {
return (
<div style={style.text}>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick={this.handleLogoutClick.bind(this)}>Yes</Button>
</div>
);
}
}
this topic helped me a lot:
Programmatically navigate using react router
I've got the following problem. I want to work with NG2 Forms. According to the angular 2 documentation, using the ngForm directive on the form and the ngControl directive on the input, the form should always have access to the validity of the input.
This works if the inputs are in the same component as the form, but as soon as I move the inputs into a child directive, they don't get the ngForm-Provider anymore.
This works:
import { Component, Input } from 'angular2/core';
import { FORM_DIRECTIVES } from 'angular/common';
#Component({
directives: [FORM_DIRECTIVES],
template: `
<form #heroForm="ngForm">
<input type="text"
[(ngModel)]="input.test"
ngControl="name">
</form>
`
})
export class FormTest1 {
public input = {
test: ""
}
}
However, this doesn't:
import { Component, Input } from 'angular2/core';
import { FORM_DIRECTIVES } from 'angular/common';
#Component({
directives: [FORM_DIRECTIVES],
template: `
<input *ngIf="data"
[(ngModel)]="data.test"
ngControl="name">
`
})
export class FormInput {
#Input() data;
}
#Component({
directives: [FormInput, FORM_DIRECTIVES],
template: `
<form #heroForm="ngForm">
<form-input
[data]="input">
</form-input>
</form>
`
})
export class FormTest1 {
public input = {
test: ""
}
}
As this throws:
EXCEPTION: No provider for t! (t -> t) in [null]
As soon as I remove the ngControl-attribute from the input, the error disappears, but the form in the parent doesn't receive any information about the input anymore. How do I go about passing the ngForm down to the child component?
Thanks in advance.
Here's a little example:
form-test.component.js
#Component({
selector: 'form-test',
directives: [FormInput, FORM_DIRECTIVES],
template: `
<form [ngFormModel]="heroForm">
<br>Is Form Valid? - {{heroForm.valid}}<br>
<br>Data: - {{input | json}}<br>
<input type="text" [(ngModel)]="input.test1" required [ngFormControl]="heroForm.controls['test1']">
<form-input [hForm]="heroForm" [data]="input">
</form-input>
<button type="submit">Submit</button>
</form>
`
})
export class FormTest1 {
public heroForm:ControlGroup;
constructor(private _builder:FormBuilder){
this.heroForm = _builder.group({
test1: ["", Validators.required],
test2: ["", Validators.required]
});
}
public input = {
test1: "",
test2: ""
}
}
form-input-test.ts
#Component({
selector: 'form-input',
directives: [FORM_DIRECTIVES,NgForm],
template: `
<label>sdsd</label>
<input type="text" [(ngModel)]="data.test2" [ngFormControl]="hForm.controls['test2']" required>
`
})
export class FormInput {
#Input() hForm:ControlGroup;
#Input() data;
}
I did two things mainly:
1- you only have access to the form in the parent object not in the child, I added another input so you can pass it along.
2-There's two ways to create a ControlGroup, one is implicitly like the one you did with ngForm and ngControl, and the other one is explicitely like I did with ngFormModel and ngFormControl, the second one gives you more control over the form so you can you things like this.
I recommend you to read this link