Call angular method in series -Highcharts - angularjs

All I'm a newbie in learning Angular and highchairs. My issue is how to call angular method in series to render charts dynamically.
I referred this link ,but i'm not understanding anything from that:
link:https://www.highcharts.com/blog/tutorials/194-using-highcharts-with-angular-js/.
link: Call an angular component method when we click on highchart series
Kindly app me to solve this.
app.component.ts
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name:string = '';
age:number;
found:boolean;
constructor(private httpClient: HttpClient) { }
onNameKeyUp(event:any){
this.name = event.target.value;
this.found = false;
}
getProfile(){
this.httpClient.get(`https://my-json-server.typicode.com/techsithgit/json-faker-directory/profiles/?name=${this.name}`)
.subscribe(
(data:any[] )=>{
if(data.length){
this.age = data[0].age;
this.found = true;
}
}
)
}
}
app.component.html
<input type ="text" (keyup) = "onNameKeyUp($event)">
<button (click)= "getProfile()">Get User Details</button>
<br>
<div *ngIf="found" >
<span>{{name}}'s age is {{age}}</span>
</div>

Related

How to access DOM element in other component in Angular 6?

I have two components header & a. In header component there is a hidden element and I want to show it from component a, but I don't know how do I do this.
header.component.html
<p>
header works!
</p>
<div #hidden_element style="display: none">
<h1>Hidden Element in header</h1>
</div>
a.component.html
<div (click)="show()">Show</div>
a.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {
constructor() { }
show() {
// code to display hidden element in header component
}
ngOnInit() {
}
}
app.component.html
<app-header></app-header>
<app-a></app-a>
You can do it by sending events between directives via a custom service. A simple example would look something like this:
// my-service.component.ts
import { Injectable } from "#angular/core";
import { Subject } from "rxjs/index";
#Injectable()
export default class MyService {
private messageSource = new Subject<string>();
listener = this.messageSource.asObservable();
send(message: string): void {
this.messageSource.next(message);
}
}
Your 'a' component will look something like this:
// a.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {
constructor(private myService: MyService) { }
show() {
// code to display hidden element in header component
this.myService.send('some message');
}
ngOnInit() {
}
}
and this is your header component:
// header.component.ts
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: []
})
export class HeaderComponent implements OnDestroy {
private serviceSubscription: Subscription;
constructor(private myService: MyService) {
this.serviceSubscription = this.myService.listener.subscribe(message => {
// TODO: Do whatever you want to do here to show the hidden element
});
}
ngOnDestroy(): void {
this.serviceSubscription.unsubscribe();
}
}

Unable to loop array of objects in angular6

I'm trying to fetch movie data from omdbapi but i'm not getting able to print this value in html
.ts
import { Component, } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _httpClient: HttpClient) {}
results: any = [];
getMovies(title) {
`enter code here`
this._httpClient.get("http://www.omdbapi.com/?apikey=d5dc2a5a&s=" + title)
.subscribe((data) => {
this.results = data;
//this.results.Search;
console.log(this.results)
})
}
}
Console value
You're probably using *ngFor in your template on results. But since you're assigning data to results and data is an Object, it's giving an error as *ngFor assumes an iterative Data Structure.
As can be seen from your Screenshot, there's a Search array on your data.
Change this.results = data; to this.results = data.Search;
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _httpClient: HttpClient) {}
results: any = [];
getMovies(title) {
this._httpClient.get("https://www.omdbapi.com/?apikey=157f9eb7&s=" + title)
.subscribe((data: any) => {
this.results = data.Search;
console.log(this.results);
})
}
ngOnInit() {
this.getMovies('The Dark Knight');
}
}
Here's a Sample StackBlitz for your ref.
You can achieve this using keyvalue pipe as below:
<div *ngFor="let item of results | keyvalue">
<b>{{item.key}}</b> : <b>{{item.value}}</b>
</div>
You are getting an object in your response. You need use ? operator in *ngFor loop like this to get array for asynchronous http service.
<ul>
<li *ngFor="let result of results?.Search">{{result.Title }}</li>
</ul>
and you can display totalResults like this :
<span>Total: {{results?.totalResults}}</span>

Angular2 Typescript View not updating data after save changes and update the array (model)

I have parent component which call a REST api to get profile (JSON) data. the parent component pass this data to child component using input (array) to create dynamic form (input fields). All fields have been created successfully. the form is saving the data to DB using API post.
Problem: If the user navigate to home page and come back to profile dynamic form the data value is showing with the data version before save (old version of the data). If I refresh the screen, then I can get the correct data. the view has not been updated when load the form again. I checked the log and the JSON data being returned updated, but the form is getting the previous version of the values.
Parent Html
<df-profile [profileData]="profileData"></df-profile>
Parent Component
import { Component, ChangeDetectorRef, Input, OnInit} from '#angular/core';
import { Http } from '#angular/http';
import { Router } from '#angular/router';
import { AuthenticationService, UserService } from '../services/index';
import { ProfileModel } from '../models/index';
#Component({
moduleId: module.id,
selector: 'user-profile',
templateUrl: 'user.profile.component.html'
})
export class UserProfileComponent implements OnInit {
profileData: ProfileModel[] = [];
public isDataAvailable: boolean = false;
constructor(
public router: Router,
private userService: UserService,
private authenticationService: AuthenticationService,
) {}
ngOnInit() {
console.info("Starting GameDay Component ngOnInit ... ...");
console.info(this.authenticationService.isLoggedIn());
if (this.authenticationService.isLoggedIn()) {
this.getData().then(() => this.isDataAvailable = true);
} else {
this.authenticationService.logout();
}
}
getData(): Promise<ProfileModel<any>[]> {
return this.userService.get.profile().then(data => {
this.profileData = data[0]['profileList'];
});
}
}
Child Dynamic Form Html
<form (ngSubmit)="form.valid && onSubmit()" [formGroup]="form">
<div class="kode-team-match" *ngFor="let item of profileData">
<ul>
<li class="home-kode-field"><df-field [field]="item.field" [form]="form"></df-field></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-12" style="text-align:center;">
<button type="submit" [disabled]="loading" class="kode-modren-btn thbg-colortwo"> Salvar</button>
</div>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
Child Dynamic Form Component
import { Component, Input, ChangeDetectorRef, OnInit } from '#angular/core';
import { FormControl, FormGroup } from '#angular/forms';
import { AuthenticationService, UserService } from '../services/index';
#Component({
moduleId: module.id,
selector: 'df-profile ',
templateUrl: 'profile.form.component.html',
providers: [ProfileControlService]
})
export class ProfileFormComponent implements OnInit {
#Input() profileData: ProfileModel[];
form: FormGroup;
payLoad = '';
constructor(
private pcs: ProfileControlService,
) {
this.profileData = [];
}
ngOnInit() {
//console.log('Starting form component ... ...');
this.form = this.pcs.toFormGroup(this.profileData);
}
onSubmit() {
this.userService.saveUserProfile(array)
.subscribe(result => {
this.isFailed = result;
if (result === true) {
this.service.success(this.translate.instant('register login'), this.translate.instant('register success'));
} else {
this.error = this.userService.errorMessage;
}
this.loading = false;
});
}
}
I'm struggling to see what I'm doing wrong here. Can anyone help?
I don't know if I need to invoke change detection and where.

Automatically update Angular page on new JSON information

I have a news app that calls information from a service. I would like to make it so that, when there is news, this is automatically added to the page.
At first, I was trying to do it by using a this.router.navigate(['/news']) in a setInterval method, but this gives the issue that if I change the page (it's a single page site), the refresh reconnects to the news page.
So, I would need something to either refresh the JSON information, or a way to stop the refresh, the moment I select another page.
The component:
import { Component, OnInit } from '#angular/core';
import { NewsService } from '../services/news.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit
{
//prop
news: any;
today =
{
releaseDate: Date()
}
//constructor
constructor(private newsService: NewsService, public router: Router)
{
//getdata
this.newsService.getNews().subscribe(response => this.news = response);
}
//methode
Refresh()
{
//redirect
setInterval(() =>
{
this.today.releaseDate = Date();
//this.router.navigate(['/news']);
}, 1000);
}
//lifeCycle
ngOnInit()
{
this.Refresh()
}
}
the service:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class NewsService
{
//constructor
constructor(private http: Http)
{
}
//methode
getNews()
{
return this.http.get('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={apikey}').map(response => response.json());
}
and the html:
<div>
<h1 style="display:inline">Latest news</h1>
</div>
<h5 style="float:right">{{today.releaseDate|date:"HH:mm:ss"}}</h5>
<hr/>
<div *ngIf="news">
<div class="newscontainer" *ngFor="let new of news.articles, let i =index">
<div class="newsimage{{i%2}}">
<img src="{{new.urlToImage}}">
</div>
<div class="newstitle">{{new.title}}</div>
<hr />
<div class="releasedate">Release date: {{new.publishedAt|date}} at {{new.publishedAt|date:"HH:mm"}}</div>
Link to Article
<div class="synopsis">{{new.description}}</div>
</div>
</div>

Angular 2 I don't know how to delete a row of a pushed Object

First let me be clear about my problem/issue:
First it was like this: https://www.dropbox.com/s/92z2oe7f4w5x2b5/conditions.jpg?dl=0 Here it deletes the last created Object in my case Conditions.
but i want to delete each condition separately like this see the red box next to each row: https://www.dropbox.com/s/ptwq6sk6da4p21k/new.jpg?dl=0
import {Component, OnInit, DynamicComponentLoader, Input} from 'angular2/core';
import {Condition} from './condition';
import {DateCondition} from './datecondition.component';
import {StringCondition} from './stringcondition.component';
import {SelectCondition} from './selectcondition.component';
import {ConditionDetailComponent} from './conditiondetail.component';
import {ConditionService} from './condition.service'
#Component({
selector: 'condition-builder',
templateUrl: 'app/conditionbuilder.component.html',
directives: [ConditionDetailComponent],
})
export class ConditionBuilderComponent implements OnInit {
conditions: Condition[] = [];
catalog: Condition[] = [];
constructor(public _conditionService: ConditionService) { }
getConditions() {
this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}
ngOnInit() {
this.getConditions();
}
onChange(conditionsIndex, selectedCondition:string): void {
this.conditions[conditionsIndex] = this.catalog.find(condition => condition.name == selectedCondition);
}
newCondition() {
this.conditions.push(this.catalog[0]);
}
deleteCondition() {
this.conditions.pop();
}
}
In the code above i'll import the getConditions with the object of conditions in my case. Does any one know how i do this and what is the best way to handle this issue?
Here i want to
import {Component, OnInit, Input, DynamicComponentLoader, ElementRef} from 'angular2/core';
import {Condition} from './condition';
import {DateCondition} from './datecondition.component';
import {StringCondition} from './stringcondition.component';
import {SelectCondition} from './selectcondition.component';
import {ConditionBuilderComponent} from "./conditionbuilder.component";
#Component({
selector: 'condition-detail',
template: '<div #child></div>'
+ '<a class="btn btn-danger" (click)="deleteCondition()"><i class="glyphicon glyphicon-minus"></i></a>'
})
export class ConditionDetailComponent implements OnInit {
#Input() condition: Condition;
dcl:DynamicComponentLoader;
elementRef:ElementRef;
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
this.dcl = dcl;
this.elementRef = elementRef;
}
ngOnInit() {
this.dcl.loadIntoLocation(this.condition, this.elementRef, 'child');
}
deleteCondition() {
HOW CAN I DELETE THE CONDITION ROW HERE?
}
Like this is the code build, ill hope it is clear for you to help me out. How does the deleteCondition method know which row he needs to deleten and how do i delete it out of the array in the code above the page?
Ill hope someone can help me out!!
You could provide the list to the sub component and remove the current element from it. This way the associated component in the loop will be removed.
The main component:
#Component({
selector: 'my-app',
template: `
<div *ngFor="#elt of data">
<my-component [elt]="elt" [data]="data"></my-component>
</div>
`,
directives: [MyComponent]
})
export class AppComponent {
constructor() {
this.data = [
{name: 'name1'},
{name: 'name2'},
{name: 'name3'},
{name: 'name4'}
];
}
}
The child component:
#Component({
selector: 'my-component',
template: `
<div>{{elt.name}} <span (click)="delete()">X</span></div>
`
})
export class MyComponent {
#Input()
elt: any;
#Input()
data: any[];
delete() {
var index = this.data.indexOf(this.elt);
this.data.splice(index, 1);
}
}
See this plunkr: https://plnkr.co/edit/o5O0Rr?p=preview.

Resources