I have in this code a method openItem(anuncio, operacao)" that runs when I click on the object that will perform the action. In this case I don't understand why when running (click) = 'checkFavorite (advert) he also performs the action. Clicking the verifyFavorite action should only run it and not openItem. Could anyone help me? thanks !!!
<div class="ali-container">
<div class="ali-linha">
<div class="ali-capa-livro">
<button *ngIf="operacao !== vis" class="ali-capa-livro-btn" (click)="openItem(anuncio, operacao)">
<img src="{{anuncio.publicacao.imagem}}" width="40%" height="40%" />
</button>
<button *ngIf="operacao === vis" class="ali-capa-livro-btn">
<img src="{{anuncio.publicacao.imagem}}" width="40%" height="40%" />
</button>
</div>
<div class="ali-detalhes-livro">
<div class="ali-titulo-livro">{{anuncio.publicacao.titulo}}</div>
<div class="ali-autores-livro linha-unica-elipissis">{{anuncio.publicacao.autores}}</div>
<span class="ali-preco">{{anuncio.preco | currency:'R$':'code'}}</span>
<span class="ali-conservacao">({{anuncio.tipoConservacao}})</span>
<div class="ali-anunciante linha-unica-elipissis">por {{anuncio.usuario.nome}}</div>
<div class="ali-anunciante linha-unica-elipissis">{{anuncio.statusAnuncio}}</div>
<span>Anúncio: {{anuncio.tipoAnuncio.nome}} {{anuncio.tipoAnuncio.valor | currency:'R$':'code' }}</span>
</div>
<div *ngIf="operacao !== vis">
<button mode="ios" class="botao-excluir-anuncio" (click)="excluir(tipo, anuncio._id, favorito)" ion-button
round text-center item-end>
<ion-icon name="trash" item-end></ion-icon>
</button>
</div>
</div>
</div>
<div *ngIf="operacao === vis">
<div *ngIf="!anuncio.favorito">
<button mode="ios" class="botao-naoefavorito-anuncio" (click)='verificarFavorito(anuncio)' ion-button round
text-center item-end>
<ion-icon name="ios-heart-outline" item-end></ion-icon>
</button>
</div>
<div *ngIf="anuncio.favorito">
<button mode="ios" class="botao-favorito-anuncio" (click)='verificarFavorito(anuncio)' ion-button round
text-center item-end>
<ion-icon name="ios-heart" item-end></ion-icon>
</button>
</div>
<div *ngIf="apenasexcluir === 1">
<button mode="ios" class="botao-excluir-anuncio" (click)="excluir(tipo, anuncio._id, favorito)" ion-button round
text-center item-end>
<ion-icon name="trash" item-end></ion-icon>
</button>
</div>
</div>
import { Component, Input, Output, EventEmitter } from '#angular/core';
import { Anuncio } from '../../models/anuncio';
import { AppBasePage } from '../../pages/app-base-page/app-base-page';
import { AnuncioDetalhePage } from '../../pages/anuncio-detalhe/anuncio-detalhe';
import { NavController, NavParams } from 'ionic-angular';
import { AppGlobal } from '../../app/app.global';
import { AppRestService } from '../../services/app-rest.service';
import { RestNovoFavorito } from '../../services/app-rest.service';
#Component({
selector: 'anuncio-list-item',
templateUrl: 'anuncio-list-item.html'
})
export class AnuncioListItemComponent extends AppBasePage {
#Input('anuncio') anuncio: Anuncio;
#Input('tipo') tipo: any;
#Input('favorito') favorito: any;
#Input('cesta') cesta: any;
#Input('operacao') operacao: any;
#Input('apenasexcluir') apenasexcluir: any;
#Output() onExcluir: EventEmitter<any> = new EventEmitter();
#Output() onDetail: EventEmitter<any> = new EventEmitter();
constructor(private rest: AppRestService, private appGlobal: AppGlobal, public navCtrl: NavController, public navParams: NavParams) {
super();
}
openItem(anuncio, operacao, apenasexcluir) {
// quando origem cesta, chama com o parametro para atualizar a cesta de acordo com o anuncio alterado
if (this.cesta) this.navCtrl.push(AnuncioDetalhePage, { anuncio: anuncio, operacao: operacao, apenasexcluir: apenasexcluir, cesta: this.cesta });
else this.navCtrl.push(AnuncioDetalhePage, { anuncio: anuncio, operacao: operacao, apenasexcluir: apenasexcluir});
}
excluir(tipo, id, favorito) {
if (tipo == 1) {
this.onExcluir.emit(favorito);
} else
this.onExcluir.emit(id);
}
verificarFavorito(id) {
if (id.favorito) {
this.excluirFavorito(id.favorito._id)
} else {
this.incluirFavorito(id._id)
}
}
async excluirFavorito(id) {
await this.rest.excluirAnuncioFavorito(id);
}
async incluirFavorito(id) {
let restNovoFavorito = new RestNovoFavorito();
restNovoFavorito.anuncio = id;
await this.rest.incluirFavorito(restNovoFavorito);
}
}
Related
I manage to fetch the product data through the URL and when I am on the product details page there is a button that allows me to add the product to a sub-collection of the logged in user.
Below is what I want:
users/{userID}/shopping/{productID}
details-product.component.html displaying information in product details
<div class="uk-container panier" *ngIf="product">
<div id="modal-center" class="uk-flex-top" uk-modal>
<div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical">
<button class="uk-modal-close-default" type="button" uk-close></button>
<img [src]="(product | async)?.imageURL" class="nav-left">
</div>
</div>
<div class="uk-child-width-1-2#s" uk-grid>
<div>
<a href="#modal-center" uk-toggle>
<img [src]="(product | async)?.imageURL" class="nav-left" alt="">
</a>
</div>
<div>
<div class="uk-dark uk-padding">
<h3> {{ (product | async)?.name }}</h3>
<hr class="uk-divider-icon">
<div class="uk-flex prix">
<p class="uk-text">
<span>{{ (product | async)?.price | currency: 'XOF' }} </span>
</p>
</div>
<hr class="uk-divider-icon">
<button class="uk-button uk-button-default uk-form-width-medium" (click)="showDialog()">
<i class='bx bxs-cart-add'></i>
J'achète le produit
</button>
</div>
</div>
</div>
</div>
shopping-cart.service.ts
import { AngularFirestore, AngularFirestoreCollection } from '#angular/fire/compat/firestore';
import "firebase/auth";
import { User } from 'src/app/models/user.model';
import { Product } from 'src/app/models/product.model';
#Injectable({
providedIn: 'root'
})
export class ShoppingCardService {
userCollection: AngularFirestoreCollection<User>;
productsCollection: AngularFirestoreCollection<Product>;
constructor(private readonly dbstore: AngularFirestore) {
this.userCollection = this.dbstore.collection('users');
this.productsCollection = this.dbstore.collection('products');
}
addToMyCart(product: Product, userID: string, qteProduct: number) {
const userDoc = this.dbstore.firestore.collection('users').doc(userID);
const productDoc = this.dbstore.firestore.collection('products').doc(product.id);
const userShoppingProduct = userDoc.collection('shopping');
return userShoppingProduct.doc(product.id).set(product);
}
}
product.service.ts
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '#angular/fire/compat/firestore';
import { Router } from '#angular/router';
import { Observable } from 'rxjs';
import { Product } from 'src/app/models/product.model';
#Injectable({
providedIn: 'root'
})
export class ProductsService {
productCollection: AngularFirestoreCollection<Product>;
constructor(private dbstore: AngularFirestore, private router: Router) {
this.productCollection = this.dbstore.collection('products', (ref) =>
ref.orderBy('category', 'desc')
);
}
getDetailProduct(productId: string): Observable<any> {
return this.productCollection.doc(productId).valueChanges();
}
}
details-product.component.ts
import { ActivatedRoute } from '#angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { User } from 'src/app/models/user.model';
import { Product } from 'src/app/models/product.model';
import { ProductsService } from '../../shared/services/products.service';
import { ShoppingCardService } from 'src/app/shared/services/shopping-card.service';
import { AngularFirestoreCollection } from '#angular/fire/compat/firestore';
import { AddToCartComponent } from './add-to-cart.component'
import { MatDialog } from '#angular/material/dialog';
#Component({
selector: 'app-details-product',
templateUrl: './details-product.component.html',
styleUrls: ['./details-product.component.css']
})
export class DetailsProductComponent implements OnInit {
quantity: number = 0;
productIdRoute: string;
isMyProduct: boolean = false;
product: Observable<Product>;
userCollection!: AngularFirestoreCollection<User>
constructor(
private route: ActivatedRoute,
private productService: ProductsService,
private shoppingCardService: ShoppingCardService,
private titleService: Title,
private dialog: MatDialog,
) {
const routeParams = this.route.snapshot.paramMap;
this.productIdRoute = String(routeParams.get('productId'));
this.product = this.productService.getDetailProduct(this.productIdRoute);
}
showDialog(): void {
const data = this.dialog.open(AddToCartComponent, {
width: '30rem',
data: { productID: this.productIdRoute },
});
console.log(data);
}
add-to-cart.component.ts
component in modal to confirm adding to cart
import { Component, OnInit, Inject } from '#angular/core';
import { MatDialog, MAT_DIALOG_DATA } from '#angular/material/dialog';
import { ShoppingCardService } from '../../shared/services/shopping-card.service';
import { Product } from 'src/app/models/product.model';
#Component({
selector: 'app-add-to-cart',
template: `
<div class="relative p-4 w-full max-w-md h-full md:h-auto">
<div class="p-6 text-center">
<svg aria-hidden="true" class="mx-auto mb-4 w-14 h-14 text-gray-400 dark:text-gray-200" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
<h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">Do you want to add this product?</h3>
<button (click)="onAddPubpik(data.product, data.userID)" type="button" class="text-white bg-gray-800 hover:bg-gray-800 focus:ring-4 focus:outline-none font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
Yes, i add to cart
</button>
</div>
</div>
`,
styleUrls: ['./details-product.component.css']
})
export class AddToCartComponent implements OnInit {
constructor(
#Inject(MAT_DIALOG_DATA) public data: { product: Product, userID: string, qteProduct: number },
private dialog: MatDialog,
private shoppingService: ShoppingCardService
) {}
ngOnInit(): void {
}
async onAddPubpik(product: Product, userID: string): Promise<void> {
this.dialog.closeAll();
const qteProduct = (product.quantity += 1);
product.isMyProduct = true;
await this.shoppingService.addToMyCart(product, userID, qteProduct);
}
}
When i confirm, in console :
On this line const qteProduct = (product.quantity += 1);, product is undefined. You’re not passing product to the matdialog component in your showDialog() method hence the error.
In My ionic 3 app the tab bar is getting disappear when navigating from side bar. All other pages are working fine. Only when routing from side bar, tab is getting disappear.
Here is my app.html
<ion-menu [content]="content" type="overlay">
<ion-content class="menubar">
<ion-list class="mainmenu">
<div class="profile">
<ion-row>
<ion-col col-4><img src="./assets/imgs/wgs-logo.png" alt=""></ion-col>
<ion-col col-8 class="j-c-center" (click)="openLandingPage()">
<ion-icon slot="start" class="landing-page-icon" name="custom-landing-page"></ion-icon>
</ion-col>
</ion-row>
</div>
<ion-item no-lines class="menuitem" *ngFor="let cate of categoryFullData; let i = index;">
<button ion-button clear menuToggle (click)="opencategory(cate.id, cate.categry)">
<img src="{{baseUrlImage}}{{cate.cateimg}}">
<p>{{cate.categry}}</p>
</button>
<ion-icon slot="end" name="ios-arrow-down" class="icon-down-arrow" (click)="menuItemHandler(i)"></ion-icon>
<ion-item-group submenu [class.visible]="showSubmenu[i]">
<ion-item no-lines class="menuitem" *ngFor="let subcate of cate.subcategories; let i = index;">
<button ion-button clear (click)="opencategory(subcate.id, subcate.categry)" menuToggle>
<img src="{{baseUrlImage}}{{subcate.cateimg}}">
<p>{{subcate.categry}}</p>
</button>
</ion-item>
</ion-item-group>
</ion-item>
<ion-item no-lines class="menuitem">
<button ion-button clear menuToggle (click)="openLandingPage()">
Sell
</button>
</ion-item>
<ion-item no-lines class="menuitem">
<button ion-button clear menuToggle (click)="openAboutUs()">
<p>About Us</p>
</button>
</ion-item>
<ion-item no-lines class="menuitem">
<button ion-button clear menuToggle (click)="openTermsAndConditions()">
<p>Terms & Conditions</p>
</button>
</ion-item>
<ion-item no-lines class="menuitem">
<button ion-button clear menuToggle (click)="openPrivacyPolicy()">
<p>Privacy Policy</p>
</button>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
Here is my app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, App, LoadingController, AlertController, ToastController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { NotificationsPage } from '../pages/notifications/notifications';
import { OrderHistoryPage } from '../pages/order-history/order-history';
import { ContactPage } from '../pages/contact/contact';
import { FeedbackPage } from '../pages/feedback/feedback';
import { HomePage } from '../pages/home/home';
import { OffersPage } from '../pages/offers/offers';
import { TermsPage } from '../pages/terms/terms';
import { HkApiproviderProvider } from '../providers/hk-apiprovider/hk-apiprovider';
import { CategoryPage } from '../pages/category/category';
import { LanguageServiceProvider } from '../providers/language-service/language-service';
import { TranslateService } from '#ngx-translate/core';
import { TabsPage } from '../pages/tabs/tabs';
import { ProductsPage } from '../pages/products/products';
import { LandingPage } from '../pages/landing-page/landing-page';
import { PrivacyPage } from '../pages/privacy/privacy';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
validEmail:any;
rootPage: any = TabsPage;
showSubmenu = [];
resposeData: any;
categoryFullData:any;
pages: Array<{title: string, component: any}>;
apptoken = {"token":""};
postData={
"user_id":"",
"token":"",
}
baseUrlImage: any;
itemsuperqty: number;
userDetails: any;
constructor(public platform: Platform, public auth:HkApiproviderProvider,public app:App, public toastCtrl: ToastController, public loadingCtrl:LoadingController, public alertCtrl:AlertController, public statusBar: StatusBar, public splashScreen: SplashScreen,public langserv : LanguageServiceProvider, translate: TranslateService) {
this.initializeApp();
this.apptoken.token = HkApiproviderProvider.gettoken();
localStorage.setItem('appconfig', JSON.stringify(this.apptoken));
langserv.getdefaultlang();
translate.setDefaultLang(langserv.defaultlang);
this.langserv.changelang('en');
this.itemsuperqty = 1;
this.baseUrlImage = auth.getimage();
if(localStorage.getItem('userData')){
const data = JSON.parse(localStorage.getItem('userData'));
this.userDetails = data.userData;
}
this.postData.token = HkApiproviderProvider.gettoken();
this.getcategorydata();
}
/* menuItemHandler(): void {
this.showSubmenu = !this.showSubmenu;
} */
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.backgroundColorByHexString('#307722');
this.splashScreen.hide();
});
}
onclickHome(){
this.nav.setRoot(HomePage , { tabIndex: 0 });
}
onclickcategory(){
this.nav.push(CategoryPage , { tabIndex: 0 });
}
onclickMyOrder(){
this.nav.push(OrderHistoryPage , { tabIndex: 1 });
}
openContact(){
this.nav.push(ContactPage , { tabIndex: 0 });
}
onclickNoti(){
this.nav.push(NotificationsPage , { tabIndex: 0 });
}
openfeedback(){
this.nav.push(FeedbackPage , { tabIndex: 0 });
}
openoffers(){
this.nav.push(OffersPage , { tabIndex: 0 });
}
openterms(){
this.nav.push(TermsPage , { tabIndex: 0 });
}
openprivacy(){
this.nav.push(TermsPage , { tabIndex: 0 });
}
openLandingPage(){
this.nav.push(LandingPage);
}
checkLogin(){
if(localStorage.getItem('userData')){
return true;
}else{
return false;
}
}
menuItemHandler(index): void {
if(this.showSubmenu[index] && this.showSubmenu[index] == false) {
this.showSubmenu[index] = true;
} else if (this.showSubmenu[index] && this.showSubmenu[index] == true) {
this.showSubmenu[index] = false;
} else {
this.showSubmenu[index] = true;
}
}
public getcategorydata()
{
let zest = this.loadingCtrl.create({
content: "Getting Data..",
duration:20000,
spinner:'crescent'
});
zest.present();
this.auth.postData(this.postData, "getcategory").then((result) => {
this.resposeData = result;
this.categoryFullData = this.resposeData.Data;
//console.log(result);
zest.dismiss();
}, (err) => {
zest.dismiss();
});
}
opencategory(category, cname){
this.nav.push(ProductsPage,{
category : category,
cname : cname,
tabIndex: 1
});
}
openAboutUs() {
this.nav.push(ContactPage);
}
openTermsAndConditions() {
this.nav.push(TermsPage);
}
openPrivacyPolicy() {
this.nav.push(PrivacyPage);
}
}
This is my tabs.html page
<ion-tabs>
<ion-tab [root]="tab6Root" class="tab-bar" tabIcon="custom-landing-page">
</ion-tab>
<ion-tab [root]="tab1Root" class="tab-bar" tabIcon="ios-home-outline">
</ion-tab>
<ion-tab [root]="tab2Root" class="tab-bar" tabIcon="ios-person-outline">
</ion-tab>
<ion-tab [root]="tab3Root" class="tab-bar" tabIcon="icon-cart-white" [tabBadge]="cartCounterManager()">
</ion-tab>
<ion-tab [root]="tab4Root" class="tab-bar" tabIcon="ios-heart-outline" [tabBadge]="wishListCounterManager()">
</ion-tab>
<ion-tab [root]="tab5Root" class="tab-bar" tabIcon="ios-search-outline">
</ion-tab>
</ion-tabs>
tabs.component.ts
import { Component } from '#angular/core';
import { ProductSearchPage } from '../product-search/product-search';
import { ProfilePage } from '../profile/profile';
import { HomePage } from '../home/home';
import { CartPage } from '../cart/cart';
import { WishListPage } from '../wishlist/wishlist';
import { NavController, NavParams } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { ProductsPage } from '../products/products';
import { LandingPage } from '../landing-page/landing-page';
#Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = HomePage;
tab2Root = ProfilePage;
tab3Root = CartPage;
tab4Root = WishListPage;
tab5Root = ProductSearchPage;
tab6Root = LandingPage;
selectedIndex: Number;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
){
}
ionViewDidLoad() {
this.selectedIndex = this.navParams.get('tabIndex') || 0;
console.log(this.selectedIndex)
}
cartCounterManager(){
return HomePage.cartData.length
}
wishListCounterManager(){
return HomePage.wishListData.length
}
}
I tried every method available but none works. Please help. Every small comments will be appreciated.
I am using a template I bought recently to build my ionic + angular app. My problem is that I am new to angular and I am trying to redirect the user when the click a button. I've been researching and I got the point where it detects the click but doesn't redirect. I tried importing "router" and other troubleshooting steps but it's not working for me. Here is my html, and ts file.
html
<!--Theme Google Card - Full Image Cards-->
<ion-content padding-top>
<ion-grid no-padding>
<ion-row *ngIf="data != null">
<ion-col col-12 col-md-6 col-lg-6 *ngFor="let item of data.items;let i = index">
<ion-card text-left box-shadow margin-bottom>
<!--Card Image-->
<div card-image>
<img [src]="item.image" />
<div watch-now text-center (click)="onEvent('onItemClick', item, $event)">
<button ion-button button-icon icon-start>
<ion-icon icon-small [name]="item.icon"></ion-icon>
{{item.iconText}}
</button >
</div>
</div>
<!--Card descriptiom-->
<ion-card-content>
<ion-card-title text-center>
<!--Card Subtitle-->
<h1 card-title>{{item.title}}</h1>
<!-- Icon Rating Star -->
<ion-icon *ngFor="let star of item.ratingStar.iconsStars; let i = index" (click)="onStarClass(item.ratingStar.iconsStars, i, $event)">
<i icon-small *ngIf="star.isActive" class="icon {{star.iconActive}}"></i>
<i icon-small *ngIf="!star.isActive" class="icon {{star.iconInactive}}"></i>
</ion-icon>
<!-- Reviews Star -->
<span span-medium>{{item.reviews}}</span>
<!--Card Body Text-->
<p margin-top card-body-text>{{item.description}}</p>
</ion-card-title>
</ion-card-content>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
TS
import { Component, Input, ViewChild } from '#angular/core';
import { IonicPage, Content } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'google-card-layout-1',
templateUrl: 'google-card.html'
})
export class GoogleCardLayout1 {
#Input() data: any;
#Input() events: any;
#ViewChild(Content)
content: Content;
slider = {};
constructor() { }
slideHasChanged(slider, index): void {
this.slider[index] = slider;
if (2 == slider._activeIndex) {
if (this.data.items) {
this.data.items.splice(index, 1);
} else {
this.data.splice(index, 1);
}
}
}
onStarClass(items: any, index: number, e: any) {
if (e) {
e.stopPropagation();
}
for (var i = 0; i < items.length; i++) {
items[i].isActive = i <= index;
}
this.onEvent("onRates", index, e);
};
onClickEvent(index): void {
if (this.slider[index]) {
this.slider[index].slidePrev(300);
}
}
onEvent(event: string, item: any, e: any) {
if (e) {
e.stopPropagation();
}
if (this.events[event]) {
this.events[event](item);
}
}
}
Firstly you have to declare your route in your routing file in my case i have one newly created component so i update my route as follow
{
path: 'admin',
canActivate: [AuthGuard],
loadChildren: './pages/admin/admin.module#AdminModule'
},
After that there are two method to navigate,
1) <button [routerLink]="['/admin']" ion-button button-icon icon-start>
2) <button (click)="navigate()" ion-button button-icon icon-start>
and in your ts file add code
navigate() {
this.router.navgateURL(['/admin']);
}
Try:
<button [routerLink]="['/path']" ion-button button-icon icon-start>
I'm using Angular 5, and I wanted to press another button to get another button.
I do not know if I would have to use the ngIf, but I do not know how to identify the previous button.
example.ts
import { Component, OnInit } from '#angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
#Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addHero({ name } as Hero)
.subscribe(hero => {
this.heroes.push(hero);
});
}
delete(hero: Hero): void {
this.heroes = this.heroes.filter(h => h !== hero);
this.heroService.deleteHero(hero).subscribe();
}
}
example.html
<ul class="heroes">
<li *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</a>
<button class="delete" title="delete hero" (click)="delete(hero)">x</button>
</li>
</ul>
In your component.ts:
#Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
showSecondButton: boolean = false;
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
}
delete(hero: Hero): void {
this.heroes = this.heroes.filter(h => h !== hero);
this.heroService.deleteHero(hero).subscribe();
this.showSecondButton = true;
}
}
In your html:
<ul class="heroes">
<li *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</a>
<button class="delete" title="delete hero" (click)="delete(hero)">x</button>
<button *ngIf="showSecondButton"> Your second button</button>
</li>
</ul>
so your best bet is to create two buttons within a div, then have a toggle that switches the button that is displayed.
Example:
<div>
<button *ngIf=!displaysecondbutton (click)='showsecondbutton()'>First Button Yo</button>
<button *ngIf=displaysecondbutton>SecondButtonYo</button>
</div>
typescript file;
displaysecondbutton = false;
showsecondbutton(){
this.displaysecondbutton = true;
}
To keep the code concise I would implement an if statement in your delete function:
public deleteConfirmed = false;
public confirmDelete = false;
delete(hero: Hero): void {
if (deleteConfirmed) {
confirmDelete = deleteConfirmed = false;
this.heroes = this.heroes.filter(h => h !== hero);
this.heroService.deleteHero(hero).subscribe();
}
else{
confirmDelete = true;
}
}
Then in your html:
<button class="delete" title="delete hero" (click)="delete(hero)">Delete</button>
<button *ngIf="confirmDelete" class="delete" title="delete hero" (click)="deleteConfirmed=true; delete(hero)">Confirm Deletion</button>
This way, you are always cycling the same function and just altering some states along the way.
I'm building ionic app for wallpaper/gallery.I want app to show wallpaper in full screen when user clicks on a particular image.
Thanks.
HTML code:
<ion-header>
<ion-navbar color="dark">
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Walldo</ion-title>
</ion-navbar>
</ion-header>
<ion-slides zoom="true">
<ion-slide>
<div class="swiper-zoom-container">
<img id="fullwall" src="some link">
</div>
<ion-label>Elephant</ion-label>
<button ion-button round (click)="download('wall.jpg')">Download</button>
</ion-slide>
</ion-slides>
TYPESCRIPT code:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-popular',
templateUrl: 'popular.html',
})
export class PopularPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad PopularPage');
}
}
It's a simple property binding:
<img [src]="theWallImageUrl" />
and in the code of the component:
this.theWallImageUrl = ...