Кнопки GitHub — это мощный способ интегрировать функциональность GitHub в ваши приложения Angular. Они обеспечивают удобство работы с пользователем и позволяют пользователям напрямую взаимодействовать с вашим репозиторием GitHub. В этой статье мы рассмотрим 10 различных методов создания кнопок GitHub в Angular, а также примеры кода для каждого метода.
Метод 1: использование официальных октиконов GitHub
GitHub предоставляет коллекцию масштабируемых векторных значков, называемых октиконами. Вы можете использовать эти значки для создания кнопок GitHub в своем приложении Angular. Вот пример:
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-github-button',
template: `
<a href="https://github.com/your-repo" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
`
})
export class GithubButtonComponent {
constructor(private sanitizer: DomSanitizer) { }
}
Метод 2: использование REST API GitHub
Вы можете использовать REST API GitHub для динамического создания кнопок GitHub с информацией о репозитории. Вот пример:
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-github-button',
template: `
<a [href]="githubRepoUrl" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
`
})
export class GithubButtonComponent {
githubRepoUrl: string;
constructor(private http: HttpClient) {
this.getRepoUrl();
}
getRepoUrl() {
this.http.get<any>('https://api.github.com/repos/your-repo')
.subscribe(repo => {
this.githubRepoUrl = repo.html_url;
});
}
}
Метод 3. Настройка кнопок GitHub с помощью CSS
Вы можете настроить внешний вид кнопок GitHub с помощью CSS. Вот пример:
.github-button {
display: inline-block;
padding: 10px 20px;
background-color: #24292e;
color: #ffffff;
text-decoration: none;
border-radius: 5px;
}
.github-button:hover {
background-color: #0366d6;
}
.github-button .octicon {
vertical-align: middle;
margin-right: 5px;
}
<a href="https://github.com/your-repo" target="_blank" class="github-button">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
Метод 4: использование кнопок Angular Material
Если вы используете Angular Material в своем проекте, вы можете использовать его компонент кнопки для создания кнопок GitHub. Вот пример:
<button mat-button color="primary" [routerLink]="['/your-repo']">
<mat-icon>code</mat-icon>
View on GitHub
</button>
Метод 5: создание повторно используемого компонента Angular
Вы можете создать повторно используемый компонент Angular специально для кнопок GitHub. Вот пример:
@Component({
selector: 'app-github-button',
template: `
<a [href]="repoUrl" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
`
})
export class GithubButtonComponent {
@Input() repoUrl: string;
}
<app-github-button [repoUrl]="'https://github.com/your-repo'"></app-github-button>
Метод 6. Добавление значков к кнопкам GitHub
Вы можете улучшить свои кнопки GitHub, добавив значки, например звездочки или количество вилок. Вот пример:
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-github-button',
template: `
<a href="https://github.com/your-repo" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
<span class="badge">{{ forksCount }}</span>
</a>
`
})
export class GithubButtonComponent {
forksCount: number;
constructor(private http: HttpClient) {
this.getForksCount();
}
getForksCount() {
this.http.get<any>('https://api.github.com/repos/your-repo')
.subscribe(repo => {
this.forksCount = repo.forks_count;
});
}
}
Метод 7: использование API GraphQL GitHub
Вместо REST API вы также можете использовать API GraphQL GitHub для получения информации о репозитории для ваших кнопок. Вот пример:
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
@Component({
selector: 'app-github-button',
template: `
<a [href]="githubRepoUrl" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
`
})
export class GithubButtonComponent {
githubRepoUrl: string;
constructor(private apollo: Apollo) {
this.getRepoUrl();
}
getRepoUrl() {
this.apollo.query<any>({
query: gql`
query {
repository(owner: "your-owner", name: "your-repo") {
url
}
}
`
}).subscribe(result => {
this.githubRepoUrl = result.data.repository.url;
});
}
}
Метод 8: использование пакета ngx-clipboard
Вы можете использовать пакет ngx-clipboard, чтобы включить копирование URL-адреса репозитория в буфер обмена при нажатии кнопки GitHub. Вот пример:
npm install ngx-clipboard
import { ClipboardService } from 'ngx-clipboard';
@Component({
selector: 'app-github-button',
template: `
<button (click)="copyToClipboard()" ngxClipboard [cbContent]="githubRepoUrl">
<span class="octicon octicon-mark-github"></span>
Copy GitHub URL
</button>
`
})
export class GithubButtonComponent {
githubRepoUrl: string;
constructor(private clipboardService: ClipboardService) {
this.getRepoUrl();
}
getRepoUrl() {
this.githubRepoUrl = 'https://github.com/your-repo';
}
copyToClipboard() {
this.clipboardService.copyFromContent(this.githubRepoUrl);
}
}
Метод 9: создание динамических кнопок GitHub на основе пользовательского ввода
Вы можете создавать кнопки GitHub динамически на основе пользовательского ввода. Вот пример:
@Component({
selector: 'app-github-button',
template: `
<a [href]="githubRepoUrl" target="_blank">
<span class="octicon octicon-mark-github"></span>
View on GitHub
</a>
`
})
export class GithubButtonComponent {
@Input() username: string;
@Input() repoName: string;
githubRepoUrl: string;
ngOnChanges() {
this.githubRepoUrl = `https://github.com/${this.username}/${this.repoName}`;
}
}
Метод 10: использование значков SVG для кнопок GitHub
Вы можете использовать значки SVG для кнопок GitHub, чтобы обеспечить большую гибкость с точки зрения дизайна. Вот пример:
<a [href]="repoUrl" target="_blank">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">
<path fill-rule="evenodd" d="M8 0C3.582 0 0 3.582 0 8c0 3.535 2.29 6.531 5.47 7.59.4.07.547-.173.547-.385 0-.19-.007-.693-.01-1.36-2.222.482-2.687-1.07-2.687-1.07-.364-.923-.888-1.17-.888-1.17-.725-.496.055-.486.055-.486.803.057 1.227.827 1.227.827.714 1.222 1.875.87 2.33.665.072-.525.278-.87.505-1.07-1.773-.2-3.634-.885-3.634-3.93 0-.867.31-1.576.823-2.13-.083-.2-.36-1.007.08-2.095 0 0 .665-.212 2.18.81.633-.177 1.31-.265 1.985-.268.675.003 1.352.09 1.985.268 1.515-1.022 2.18-.81 2.18-.81.442 1.088.165 1.895.082 2.095.513.554.823 1.263.823 2.13 0 3.053-1.864 3.727-3.643 3.922.287.245.543.728.543 1.467 0 1.06-.01 1.918-.01 2.18 0 .213.145.461.55.383C13.72 14.527 16 11.53 16 8c0-4.418-