Ionic5: установка нижнего колонтитула на всех страницах приложения с помощью sharedModule и управление им (включение / выключение) из app.component
Я создал новое приложение с помощью Ionic5 с меню. Я пытаюсь использовать нижний колонтитул на нескольких страницах (теперь только на домашней странице). Сначала я создал SharedModule и импортировал его в массив импорта app.module.ts. Я добавил компонент нижнего колонтитула в массив объявлений и экспорта файла shared.module.ts. Также я добавил SharedModule в массив импорта каждого page.module.ts и, наконец, добавил
<app-footer>
в каждом page.html. Он работает должным образом, показывая нижний колонтитул на всех страницах. Но теперь мне нужно контролировать (включать / выключать) этот нижний колонтитул из моего app.component в ответ на определенное событие, например, когда Интернет недоступен (эта часть не является проблемой).
footer.component.ts
import { Component, OnInit } from '@angular/core';
import { FooterService } from 'src/app/footer.service';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss'],
})
export class FooterComponent implements OnInit {
public FooterEnabled: boolean= false;
constructor() { }
ngOnInit() {
}
}
Переменная FooterEnabled контролирует, отображается ли нижний колонтитул или нет, и его необходимо изменять из app.component
footer.component.html
<div class="footer-conn" *ngIf="FooterEnabled">
Alert!
</div>
sharedfooter.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FooterComponent } from '../components/footer/footer.component';
@NgModule({
declarations: [FooterComponent],
imports: [
CommonModule
],
exports: [
FooterComponent, CommonModule
]
})
export class SharedFooterModule { }
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { Network } from '@ionic-native/network/ngx';
import { SharedFooterModule } from './shared/sharedfooter.module';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
SharedFooterModule
],
providers: [
StatusBar,
SplashScreen,
Network,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Network } from '@ionic-native/network/ngx';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
public selectedIndex = 0;
public appPages = [
{
title: 'Página 1',
url: 'home',
icon: 'mail'
},
{
title: 'Página 2',
url: 'pagina2',
icon: 'paper-plane'
},
{
title: 'Página 3',
url: 'pagina3',
icon: 'heart'
}
];
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private network: Network
) {
this.initializeApp();
}// Fin constructor
no_internet() {
alert("No internet!")
// In this point make FooterEnabled = true (from the footer component)
}
si_internet() {
alert("Whith internet!")
//In this point make FooterEnabled = false (from the footer component)
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
ngOnInit() {
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
setTimeout(() => {
if (this.network.type !== 'none') {
this.si_internet();
}
else {
this.no_internet();
}
}, 1000);
});
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
setTimeout(() => {
if (this.network.type !== 'none') {
this.si_internet();
}
else {
this.no_internet();
}
}, 3000);
});
const path = window.location.pathname.split('/')[1];
if (path !== undefined) {
this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
}
}
}
home.module.ts (как пример)
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { HomePageRoutingModule } from './home-routing.module';
import { HomePage } from './home.page';
import { SharedFooterModule } from '../shared/sharedfooter.module';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HomePageRoutingModule,
SharedFooterModule
],
declarations: [HomePage]
})
export class HomePageModule {}
Я пробовал использовать сервис, импортированный в footer.component и app.component.ts, который реализует наблюдаемые объекты, но это не сработало. Буду признателен за ваш вклад!!
1 ответ
Возможно , вы можете сделать это, как показано ниже, добавьте ввод в свой компонент нижнего колонтитула:
footer.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss'],
})
export class FooterComponent implements OnInit {
@Input() FooterEnabled : string;
//public FooterEnabled: boolean= false;
constructor() { }
ngOnInit() {
}
}
footer.component.ts
<div class="footer-conn" *ngIf="FooterEnabled == 'on'">
Alert!
</div>
на вашем app.component.ts добавьте новый статус varibale:
no_internet() {
alert("No internet!")
this.status = 'on'
}
si_internet() {
alert("Whith internet!")
this.status = 'off'
}
поместите его в app.component.html как:
<app-footer FooterEnabled="status" ></app-footer>