I've created simple 'slider' structural directive in angular.
Is there any way to make it alive with animations, how can I bind some animation to my private next() and prev() functions so when the user clicks next or prev content will smoothly go aside and a new content will appear, or something in that kind.
import { Directive, TemplateRef, ViewContainerRef, Input, OnInit } from '#angular/core';
#Directive({
selector: '[_slide]'
})
export class CustomSlideDirective implements OnInit {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
){}
private index: number = 0;
private context: any;
#Input('_slideFrom') items: any[];
ngOnInit(){
this.context = {
$implicit: this.items[this.index],
next: () => this.next(),
prev: () => this.prev(),
}
this.viewContainer.createEmbeddedView(this.templateRef,this.context)
}
private next(){
this.index++
if(this.index === this.items.length)this.index = 0
this.context.$implicit = this.items[this.index]
}
private prev(){
this.index--
if(this.index === -1)this.index = this.items.length - 1
this.context.$implicit = this.items[this.index]
}
}
Here is the link to stackblitz live demo
https://stackblitz.com/edit/angular-k4aeg4
Related
I want to refresh my webview when a button in the component is clicked.
I can't find a way to do so.
webview.components.ts code:
import {
...
}
#BasePage()
#Component({
selector: "ns-webview",
templateUrl: "./webview.component.html",
styleUrls: ["./webview.component.css"],
})
export class WebviewComponent implements AfterViewInit {
#ViewChild("webView", { static: false }) webView: ElementRef;
private noData: boolean = false;
private dataLoaded: boolean = false;
private schwellwerteLoaded: boolean = false;
public isLoading = true;
public graphPeriod = 1440;
oLangWebViewInterface;
constructor(
private uiService: UIService,
private dataService: DataService,
private authenticationService: AuthenticationService,
private route: ActivatedRoute,
private injector: Injector
) {}
ngAfterViewInit() {
setTimeout(() => {
this.isLoading = false;
}, 1000);
orientation.setOrientation("landscape");
this.setupWebViewInterface();
}
ngOnDestroy() {
console.log("destroy");
orientation.enableRotation();
}
onSubmit(period: number){
// let webView: WebView = this.webView.nativeElement;
let graphData = new GraphdataWrapper();
this.graphPeriod=1440;
this.graphPeriod= this.graphPeriod + period
console.log(this.graphPeriod)
this.load(graphData);
// this.webView.reload();
}
...
}
this.webview.reload is not working for whatever reason.
I have no clue why this is the case.
If you have any idea im glad to hear it.
Cheers!
You can just use the reload() method of the WebView
In your HTML file you will have something like this
<Button text="Refresh" (tap)="refresh()"></Label>
<WebView (loaded)="onWebViewLoaded($event)" src="https://www.google.com" ></WebView>
And then in your js/ts file you'll have something like
onWebViewLoaded(webargs) {
this.webview = webargs.object;
}
refresh() {
this.webview.reload();
}
I have created a website in angular7 in which we have fire the function from 1 component to another component function is fire properly but value are not reflect in the html below we have shared updated fiddle:
//Component1.
import { Component, OnInit } from '#angular/core';
import { Router,NavigationExtras } from "#angular/router";
import {UserService} from "../../service/user.service";
import { FormGroup, FormBuilder, FormControl, FormGroupDirective, NgForm, Validators } from '#angular/forms';
import { DashboardComponent } from '../../dashboard/dashboard.component';
declare var $: any;
#Component({
selector: 'app-innerheader',
templateUrl: './innerheader.component.html',
styleUrls: ['./innerheader.component.css'],
providers : [DashboardComponent]
})
export class InnerheaderComponent implements OnInit {
//declare global varible here....
private loggedUserObject : any = {};
private userImageUrl : any;
constructor(
private router : Router,
private service : UserService,
private formBuilder: FormBuilder,
private dashboard : DashboardComponent) {
}
ngOnInit() {
}
//unblockUser for unblock user
unblockUser(user : any) {
//pass the dataparam in the backend....
var data = {
"user_id" : this.loggedUserObject.user_id,
"block_user_id" : this.selectedUser.id
}
//here we will set url via key wise....
var url = '/api/un-block-user-profile';
//saveDetail function for save data in db...
this.service.saveDetail(data, url).subscribe( (data : any) => {
if(data.status) {
$('#BlockedListModal').on('hidden.bs.modal', function () {
this.dashboard.getUserDetail();
})
//her we will remove user from the updated list of block user...
var index = this.blockUserlist.findIndex(x=>x.id == this.selectedUser.id);
if(index != -1) {
this.blockUserlist.splice(index, 1);
}
//remoive card after accept
this.currentElement.remove();
this.service.successAlert(data.message);
}
});
}
}
//header compeonet 2: here we will fire function from another compeonet
getDashboardDetail() {
//hold user info
var data = {
"user_id" : this.currentUserObject.user_id
}
var url = '/api/time-line-list';
//createUser function for create user in DB
this.service.saveDetail(data, url).subscribe( (data : any) => {
if(data.status) {
if(data.result.article_info.length >0) {
if(this.dashboardArticleList.length == 0) {
this.dashboardArticleList = data.result.article_info;
} else {
this.dashboardArticleList = this.dashboardArticleList.concat(data.result.article_info);
}
}
}
});
}
//In the 2nd Component we have show listing inside model.i have reload the list after close model. please check and tell me what the wrong in my code?
I am new to angular 7 and didn't find any proper answer for similar questions posted.
I am getting Property 'subscribe' does not exist on type 'void' in angular-cli. I tried importing subscribe from rxjs but didn't find that library.
The problem is in the UpdateRecord Function!
product.component.ts code:
the code bellow is exist in compoent.ts of product
import { Component, OnInit } from '#angular/core';
import { ProductService } from 'src/app/shared/product.service';
import { NgForm } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { filter, map } from 'rxjs/operators';
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
constructor(private service : ProductService, private toastr : ToastrService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form?: NgForm) {
if (form != null)
form.resetForm();
this.service.formData = {
ProductID: null,
ProductName: '',
ProductDescription: '',
Price: 0.00,
Image: '',
Qte: null
}
}
onSubmit(form: NgForm) {
if (form.value.ProductID == null)
this.insertRecord(form);
else
this.updateRecord(form);
}
insertRecord(form: NgForm) {
this.service.postProduct(form.value).subscribe(res => {
this.toastr.success('Inserted successfully', 'Product. Register');
this.resetForm(form);
this.service.refreshList();
});
}
updateRecord(form: NgForm) {
this.service.putProduct(form.value).subscribe(res => {
this.toastr.success('Updated successfully', 'Product. Update');
this.resetForm(form);
this.service.refreshList();
});
}
}
product.service.ts code :
the code bellow is exist in service file related to product
import { Injectable } from '#angular/core';
import { Product } from './product.model';
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: 'root'
})
export class ProductService {
formData : Product
list : Product[]
readonly rootURL= 'http://localhost:50369/api'
constructor(private http : HttpClient) { }
postProduct(formData : Product){
return this.http.post(this.rootURL+'/Product', formData);
}
refreshList(){
return this.http.get(this.rootURL+'/Product')
.toPromise().then(res => this.list = res as Product[]);
}
putProduct(formData : Product){
this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
}
Thanks in advance,
I missed return :
So in putProduct function in product.service.ts is updated to be :
putProduct(formData : Product){
return this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
And it's working now!
Your HttpClient.put function seems to be incorrectly used (you are passing the class as parameter when you should be passing the object).
Look for the function updateHero() in this StackBlitz example.
/** PUT: update the hero on the server. Returns the updated hero upon success. */
updateHero (hero: Hero): Observable<Hero> {
httpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}
I have a snackbar component which I have created like this!
import {Component, ViewEncapsulation, OnInit, OnDestroy} from '#angular/core';
import {
MatSnackBar,
MatSnackBarConfig,
MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '#angular/material';
import { Subscription } from 'rxjs';
import { AuthenticationService } from "../../services/authentication.service";
#Component({
selector: 'snack-message',
templateUrl: './messages.component.html',
styleUrls: [ './mesaages.component.scss' ],
encapsulation: ViewEncapsulation.None
})
export class SnackBarMessages implements OnInit, OnDestroy {
action: boolean = true;
setAutoHide: boolean = true;
autoHide: number = 2000;
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'bottom';
private showMessageSub: Subscription;
messageData: object;
addExtraClass: boolean = false;
constructor(public snackBar: MatSnackBar, public authenticationService: AuthenticationService) {
}
ngOnInit() {
this.messageData = this.authenticationService.getMessageData();
this.showMessageSub = this.authenticationService.getMessageListener()
.subscribe(data => {
this.messageData = data;
});
this.openMessageSnackBar(this.messageData);
}
openMessageSnackBar(data) {
let config = new MatSnackBarConfig();
config.verticalPosition = this.verticalPosition;
config.horizontalPosition = this.horizontalPosition;
config.duration = this.setAutoHide ? this.autoHide : 0;
this.snackBar.open(data.message, data.action, config);
}
ngOnDestroy() {
if (this.showMessageSub) {
this.showMessageSub.unsubscribe();
}
}
}
I have added subject and i have created a subscription which listens to the messageListener in my Authentication Service. Then i call next with my subjectListener with the data I want to pass. I am not getting any call on my component. I don't understand why ? This is my Service!
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Subject } from 'rxjs';
import { Router, ActivatedRoute } from '../../../node_modules/#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private mesageListener = new Subject<object>();
private messageData: object;
getMessageListener() {
return this.mesageListener.asObservable();
}
getMessageData() {
return this.messageData;
}
createUser(email: string, password: string) {
const userData: AuthModel = {
email: email,
password: password
}
const requestPath = this.getModes()[`${this.navigatedFrom}`];
this.http.post(`http://localhost:3000/api/${requestPath}/signup`,userData)
.subscribe(response => {
this.messageData = {
message: 'Sign Up Successful. Please Login now!',
action: 'Ok! Got it.'
}
this.mesageListener.next(this.messageData);
});
}
}
Try to use new BehaviorSubject<object>(null); for mesageListener .
you can see more details on Subject and BehavoiurSubject here : angular2-difference-between-a-behavior-subject-and-an-observable/
In Component subscribe to the value of Observable. It should work.
I have this component
#Component({
templateUrl: './app/component/template/actualstate.template.html',
styleUrls: ['./app/component/style/actualstate.style.css'],
pipes: [MomentPipe, CapitalizePipe]
})
export class ActualStateComponent implements OnInit {
public room: Room;
constructor(private roomService: RoomService) {
roomService.roomSelected$.subscribe(room => this.onRoomSelected(room));
}
onRoomSelected(room: Room) {
this.room = room;
console.log("room", room);
}
}
and this other component
#Component({
templateUrl: './src/admin/template/admin.template.html',
styleUrls: ['./src/admin/style/admin.style.css'],
providers: [UserService]
})
export class AdminComponent{
constructor ( private roomService: RoomService) {
}
onClick () {
this.roomService.selectRoom("","");
this.router.navigate(['ActualState']);
}
}
}
, this service :
#Injectable()
export class RoomService {
private route_room = "public/mock/room.json";
public roomSelected$: EventEmitter<Room>;
constructor (private http: Http) {
this.roomSelected$ = new EventEmitter();
}
public selectRoom (subdomain: string, id: string) {
// pick the right room
let room = ...
this.roomSelected$.emit(room);
}
private handleError (error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
}
And this template :
<div class="actual-state" *ngIf="room">
<h3>Salle {{ room.name }}
</h3>
</div>
The purpose is :
Admin component (user click on some button)
-> Listener OnClick calls a method on service roomService
-> roomService emit an event (that is public)
-> appComponent listen to this event (.subscribe)
I have no clue why this is not working. The <h3> is never showing .. even though the console.log(room) display something in the console...
How does this data binding working ? Because it just looks like data are not two-way bound
...
EDIT : i understood the problem, it was related to the routing i made. in fact i did'nt understand the fact that component of a route is destroyed when you change the route
I guess you need to subscribe
return this.http.get(this.route_room)
.map(res => res.json())
.do(data => {
this.roomSelected$.emit(data);
})
.subscribe(value => {})
.catch(this.handleError);